The Masterpiece Mom

  • Home
  • About Us
  • The Story
  • Topics
    • Encouragement
    • Faith
    • Family
    • Home
    • Masterpiece Weekend
    • Mothering
    • Printables
    • Relationships
    • The Podcast
    • Work
  • The Podcast
  • Speaking
  • Contact
Home » Misc » How to add child node in xml using java

How to add child node in xml using java


The Apache Groovy programming language

The most common way of querying XML in Groovy is using GPath:

GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identified. In this sense, it has similar aims and scope as XPath does for XML. The two main places where you use GPath expressions is when dealing with nested POJOs or when dealing with XML

It is similar to XPath expressions and you can use it not only with XML but also with POJO classes. As an example, you can specify a path to an object or element of interest:

  • a.b.c → for XML, yields all the <c> elements inside <b> inside <a>

  • a.b.c → all POJOs, yields the <c> properties for all the <b> properties of <a> (sort of like a. getB().getC() in JavaBeans)

For XML, you can also specify attributes, e.g.:

  • a["@href"] → the href attribute of all the a elements

  • a.'@href' → an alternative way of expressing this

  • a.@href → an alternative way of expressing this when using XmlSlurper

Let’s illustrate this with an example:

static final String books = '''
 <response version-api="2.0">
 <value>
 <books>
 <book available="20">
 <title>Don Quixote</title>
 <author>Miguel de Cervantes</author>
 </book>
 <book available="14">
 <title>Catcher in the Rye</title>
 <author>JD Salinger</author>
 </book>
 <book available="13">
 <title>Alice in Wonderland</title>
 <author>Lewis Carroll</author>
 </book>
 <book available="5">
 <title>Don Quixote</title>
 <author>Miguel de Cervantes</author>
 </book>
 </books>
 </value>
 </response>
 '''

2.

1. Simply traversing the tree

First thing we could do is to get a value using POJO’s notation. Let’s get the first book’s author’s name

Getting node value

def response = new XmlSlurper().parseText(books)
 def authorResult = response.value.books.book[0].author
 
 assert authorResult.text() == 'Miguel de Cervantes'

First we parse the document with XmlSlurper and the we have to consider the returning value as the root of the XML document, so in this case is "response".

That’s why we start traversing the document from response and then value.books.book[0].author. Note that in XPath the node arrays starts in [1] instead of [0], but because GPath is Java-based it begins at index 0.

In the end we’ll have the instance of the author node and because we wanted the text inside that node we should be calling the text() method. The author node is an instance of GPathResult type and text() a method giving us the content of that node as a String.

When using GPath with an xml parsed with XmlSlurper we’ll have as a result a GPathResult object. GPathResult has many other convenient methods to convert the text inside a node to any other type such as:

  • toInteger()

  • toFloat()

  • toBigInteger()

  • …​

All these methods try to convert a String to the appropriate type.

If we were using a XML parsed with XmlParser we could be dealing with instances of type Node. But still all the actions applied to GPathResult in these examples could be applied to a Node as well. Creators of both parsers took into account GPath compatibility.

Next step is to get the some values from a given node’s attribute. In the following sample we want to get the first book’s author’s id. We’ll be using two different approaches. Let’s see the code first:

Getting an attribute’s value

def response = new XmlSlurper().parseText(books)
 
 def book = response.value.books.book[0] (1)
 def bookAuthorId1 = book.@id (2)
 def bookAuthorId2 = book['@id'] (3)
 
 assert bookAuthorId1 == '1' (4)
 assert bookAuthorId1.toInteger() == 1 (5)
 assert bookAuthorId1 == bookAuthorId2
1 Getting the first book node
2 Getting the book’s id attribute @id
3 Getting the book’s id attribute with map notation ['@id']
4 Getting the value as a String
5 Getting the value of the attribute as an Integer

As you can see there are two types of notations to get attributes, the

Both of them are equally valid.

2.2. Flexible navigation with children (*), depthFirst (**) and breadthFirst

If you ever have used XPath, you may have used expressions like:

More or less we have their counterparts in GPath with the shortcuts * (aka children()) and ** (aka depthFirst()).

The first example shows a simple use of *, which only iterates over the direct children of the node.

Using *

def response = new XmlSlurper().parseText(books)
 
 // .'*' could be replaced by .children()
 def catcherInTheRye = response.value.books.'*'.find { node ->
 // node.@id == 2 could be expressed as node['@id'] == 2
 node.name() == 'book' && node.@id == '2'
 }
 
 assert catcherInTheRye.title.text() == 'Catcher in the Rye'

This test searches for any child nodes of the "books" node matching the given condition. In a bit more detail, the expression says: Look for any node with a tag name equal to 'book' having an id with a value of '2' directly under the 'books' node.

This operation roughly corresponds to the breadthFirst() method, except that it only stops at one level instead of continuing to the inner levels.

What if we would like to look for a given value without having to know exactly where it is. Let’s say that the only thing we know is the id of the author "Lewis Carroll" . How are we going to be able to find that book? Using ** is the solution:

Using **

def response = new XmlSlurper().parseText(books)
 
 // .'**' could be replaced by .depthFirst()
 def bookId = response.'**'.find { book ->
 book.author.text() == 'Lewis Carroll'
 }.@id
 
 assert bookId == 3

** is the same as looking for something everywhere in the tree from this point down. In this case, we’ve used the method find(Closure cl) to find just the first occurrence.

What if we want to collect all book’s titles? That’s easy, just use findAll:

def response = new XmlSlurper(). parseText(books)
 
 def titles = response.'**'.findAll { node -> node.name() == 'title' }*.text()
 
 assert titles.size() == 4

In the last two examples, ** is used as a shortcut for the depthFirst() method. It goes as far down the tree as it can while navigating down the tree from a given node. The breadthFirst() method finishes off all nodes on a given level before traversing down to the next level.

The following example shows the difference between these two methods:

depthFirst() vs .breadthFirst

def response = new XmlSlurper().parseText(books)
 def nodeName = { node -> node.name() }
 def withId2or3 = { node -> node.@id in [2, 3] }
 
 assert ['book', 'author', 'book', 'author'] ==
 response.value.books.depthFirst().findAll(withId2or3).collect(nodeName)
 assert ['book', 'book', 'author', 'author'] ==
 response.value.books. breadthFirst().findAll(withId2or3).collect(nodeName)

In this example, we search for any nodes with an id attribute with value 2 or 3. There are both book and author nodes that match that criteria. The different traversal orders will find the same nodes in each case but in different orders corresponding to how the tree was traversed.

It is worth mentioning again that there are some useful methods converting a node’s value to an integer, float, etc. Those methods could be convenient when doing comparisons like this:

helpers

def response = new XmlSlurper().parseText(books)
 
 def titles = response.value.books.book.findAll { book ->
 /* You can use toInteger() over the GPathResult object */
 [email protected]() > 2
 }*.title
 
 assert titles.size() == 2

In this case the number 2 has been hardcoded but imagine that value could have come from any other source (database…​ etc. ).

Node Relationships | XML | XML Tutorial

by XML Tutorial

Understanding how XML node relationships function is a prerequisite of document manipulation, addressing and and queries (such as XPATH). An XML document can define the following relationships between the various nodes. In each case the relationship is determined from the context of the current node.

  • Parent
  • Child
  • Sibling
  • Ancestor
  • Descendent

The hypothetical bookstore example is used (once again) to assist in illustrating each of the various relationships between nodes:

<?xml version="1.0" encoding="UTF-8"?>
<library>
<category name="dogs">
<book>
<title lang="english">All about dogs</title>
<author>Someone</author>
<isin>true</isin>
<daysuntilreturn>0</daysuntilreturn>
<price>15.10</price>
</book>
</category>
<category name="cats">
<book>
<title lang="english">All about cats</title>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>3</daysuntilreturn>
<price>12. 00</price>
</book>
<book>
<title lang="zulu">Konke mayelana ikati</title>
<author>Else</author>
<isin>true</isin>
<daysuntilreturn>0</daysuntilreturn>
<price>25.99</price>
</book>
</category>
</library>

Parent Relationship

The parent node is always one level higher than the current node with a direct relationship between the current node and the parent node. A node can only have one parent node; however, a parent node can have zero or more child nodes.

Child Relationship

Child nodes are always one level lower than the current node with a direct relationship between the current node and any child nodes. A node can have zero or more children.


Sibling Relationship

Sibling nodes are always on the same level of the document hierarchy. Each sibling shares the same parent node, in other words, a parent has children which are siblings. A node can have zero or more siblings.


Ancestor Relationship

Ancestor nodes are further up in the document hierarchy. A node is an ancestor if there is a direct path from the current node up through the relationships e.g.. parent, grandparent, great-grand parent and etc.

  • A parent node is an ancestor of the current node.
  • The documents’ root node is the highest level node and is an ancestor of every other node in the document.
  • The root node itself cannot have an ancestor or parent


Descendant Relationship

Descendant nodes are further down in the document hierarchy from the current node. There must be a direct path from the current node to the node in question via the relationships.

  • A child node is a descendent
  • The child of a child, of a child…, of a child is a descendent of the current node.
  • Every node in the document is a descendent of the root node


Posted in XML, XPATH and tagged Tutorial.

Root Node - JavaTutor.net

Books → Thinking In Java Enterprise (Russian translation)

The root node is an XPath node that contains the entire XML document; this is the best place to start. In the tij_menu.xml example, the root node will contain a element. In an XPath expression, the root node indicated by a single slash -/.

The root node is different because it has no parent. It always has at least one child node. The string value of the root node is the concatenation of all child text nodes of the root node. Let's Let's start our transformation from tij_menu.xml to menu.html by adding action templates for the root node. Here is menu1.xsl:

      Menu       

Now our output is tamed, but we don't have anything from our file tij_menu. xml. All text from child nodes is lost. Here is menu1.html:

    Menu    

We have dived into our simple xml file only to the level root element. We have printed an explicit shell of the HTML file. Next task - is to go through the data structure of our tij_menu.xml. Since we are dealing with the tree structure of the XML document, and we have just processed the root node - this means that we simply apply these templates to the child nodes that match the patterns. This is done using the element.

At this point, we need to add two parts to our XML file. First, we need more rules to handle the various menu items. Second, we need to have a processor that takes care of the content of the rule.

      Menu        


, Phone:

Inside the root rule, I added the tag. It transforms all child nodes of the root element. Because the root element contains only one element, , the rule will be added to handler.

is a rule that will be overridden when the XSLT processor leaves the tag. Since only in this tag we need to transform the data. This data will be the heading for our restaurant menu - restaurant name, address and phone number.

The output after translation looks like this:

    Menu   

TIJ's Restaurant

108 Java Sapien Avenue


Wayne, PA
Phone: 610-687-1234

Now let's build the menu. Each restaurant has at least one

element, the element has and the element has a . So it remains for us to add the rest of the rules for processing these elements.

      Menu        


,

Menu

:
    Price:

The

element has no text nodes, only elements. Thus, the goal when working with a menu template is to create menu groups so that they are correctly demarcated and called the menu group template.

The menu group has an attribute that describes the type of menu group. This is the desc attribute of the element. The "@" symbol must be placed in front of the attribute name so that the value is selected using the tag value-of - . the rest of the rule other than described, performs settings for a list element within a group menu - .

Rule for bold product name, then creates an unordered list for the remaining items . Because some menu items have descriptions and some do not have, the rule is created specifically for the description. If the menu item has a description, the rule will be called, and the description text node will be passed to the text( ) method of the selected attribute field.

This is what the final HTML form looks like.

Nothing fancy but you should have a good insight into the capabilities of XSLT.

← XML to HTML: Menu Display Conclusion →

KNOW INTUIT | Lecture | Introduction to XML. The structure of the XML document. XML DOM Object Model

< Solo work 8 || Lecture 9 : 123456

Abstract: The purpose of the lecture: to show how the possibilities of document markup are extended using the XML language as an example. Present the structure of an XML document and the principles for controlling its content. Show some of the control over the structure and appearance of an XML document in the browser using the XML DOM API.

Keywords: SGML, markup language, ISO, language attribute, HTML, information, Web, dtd, search, group, SUN, XML, markup language, text format, hierarchical data model, XDR, SAX, xbase, language rules, value, user, attribute, IDREF, link, file, internal schema, fully qualified name, syntax, queue, XSD, schema, w3c, simple type, space, prefix, data type, complex type, notation, list, whitespace, occurrence, program , DOM, object, microsoft, instruction, timetable, loading, web page, browser, error message, access, interface, DOM XML, firstChild, child, node deletion, Internet, API, serial access, parser, API, analysis, Java, XSLT transformation, css, XSL, XSLT, Windows, GNU, namespace, XHTML, sorting, tree, display, support, path, language, formatting, presentation, PDF, RTF, databases, engines, embeds, SQL

Introduction to XML

In 1986, long before the idea of ​​the Web was born, the Standardized Generalized Markup Language (SGML) was approved as the international standard (ISO 8879) for defining languages markup, even though SGML has been around since the late sixties. It was used to describe markup languages, while allowing the author to give formal definitions to each element and attribute of the language.

HTML was originally just one of the SGML applications. He described the rules by which information should be prepared for the World Wide Web. Thus, HTML is a set of SGML prescriptions, formulated as a Document Type Definition (DTD), that explain exactly what tags and elements stand for. The HTML DTD schema is stored in the web browser.

The shortcomings of the HTML language include the following:

  1. HTML has a fixed set of tags . You cannot create your own tags that other users understand.
  2. HTML is exclusively data presentation technology . HTML does not carry any information about the meaning of the content contained in the tags.
  3. HTML - flat language . The significance of tags is not defined in it, so it cannot be used to describe the data hierarchy.
  4. Browsers are used as a platform for applications . HTML does not have enough power to create web applications at the level that web developers are currently striving for. For example, it is impossible to develop an application for professional document processing and searching in HTML language.
  5. High volumes of network traffic . Existing HTML documents used as applications overload the Internet with large amounts of traffic in client-server systems. An example would be to send a large document across a network when only a small portion of the document is needed.

Thus, on the one hand, the HTML language is a very convenient document markup tool for use on the Web, and on the other hand, a document marked up in HTML has little information about its content. If one or another document carries sufficiently complete information about its content, it becomes relatively easy to carry out automatic generalized processing and search in the file that stores the document. The SGML language allows you to store information about the content of the document, but due to its complexity, it has never been used as widely as HTML.

A group of SGML experts led by Jon Bosak of Sun Microsystems began work on creating a subset of SGML that could be adopted by the Web community. It was decided to remove many non-essential SGML features. The language thus rearranged was called XML . The simplified version proved to be significantly more accessible than the original, with only 26 pages of specs compared to over 500 pages of SGML specs.

Let's take a closer look at the structure and features of this language.

XML ( eXtensible Markup Language ) is the W3C recommended markup language. XML is a text format designed for storing structured data, for exchanging information between programs, and for creating specialized markup languages ​​on its basis. XML is a simplified subset of the SGML language.

Language XML has the following values:

  • This is a human-oriented document format that is understandable by both humans and computers.
  • Supports Unicode.
  • Basic data structures such as records, lists, and trees can be described in XML format.
  • This is a self-documenting format that describes the structure and field names as well as the field values.
  • Has a well-defined syntax and parsing requirements to keep it simple, efficient, and consistent.
  • Widely used for document storage and processing;
  • This is a format based on international standards;
  • The hierarchical structure of XML is suitable for describing almost any type of document;
  • This is plain text, free of licenses and restrictions of any kind;
  • Platform independent;
  • Is a subset of SGML for which a lot of experience has been accumulated and specialized applications have been created;

Known shortcomings of the language include the following:

  • The XML syntax is redundant.
    • The size of the XML document is much larger than the binary representation of the same data (about 10 times).
    • The size of an XML document is significantly larger than a document in alternative textual data transfer formats (eg JSON , YAML ) and especially in data formats optimized for a particular use case.
    • XML redundancy can affect application performance. The cost of storing, processing and transmitting data is increasing.
    • For many tasks, the full power of XML syntax is not needed, and much simpler and more performant solutions can be used.
  • XML namespaces are hard to use and difficult to implement in XML parsers.
  • XML does not have built-in support for data types. It does not contain the concepts of "integers", "strings", "dates", "boolean values", etc.
  • The hierarchical data model offered by XML is limited compared to the relational model and object-oriented graphs.

Generally speaking, XML can be viewed not only as a new markup language, but also as the basis for a whole family of technologies:

Table 13.1. XML family structure.
XML XML 9 technical advice0045
DTD Document type definition (schema)
XDR Reduced XML Format (Microsoft Schema)
XSD XML Schema Definition (W3C Schemas)
Namespace Method for determining element and attribute names
XPath XML Path Language
XLink XML Link Language
XPointer XML pointer language
DOM Document Object Model API
SAX Simple API for XML
XSL Extensible Style Sheet Language
XSL-FO XSL formatting objects
XSLT XSL Transformation Language
XInclude XML Include Syntax
Xbase XML Base URI Syntax

Essentially, XML serves as a metalanguage for describing the structure of other languages. The relationship between SGML, XML, HTML and some other languages ​​is shown in the following diagram:

enlarge image
13.1. Relationship between SGML, XML and HTML.

An important difference between XML and HTML is the great attention paid to control over how exactly the rules of the language are followed when marking up documents. Depending on this, it is customary to allocate well-formed and valid XML documents .

An XML document is well-formed if it conforms to all of the XML syntax rules.

Checking the validity of a document involves the following actions:

  • Verifies that the order of elements and attributes is fully consistent with the content of the document or certain rules.
  • Data type control (achieved by using the appropriate schema).
  • Data integrity control to ensure optimal information exchange over the Web using transactions.
  • Let us now consider the basic syntactic rules for constructing XML documents.

    • XML document contains one and only one root element containing all other elements
    • Child elements contained in root element must be properly nested.
    • Names of elements follow the rules:
      • The name begins with a letter, underscore, or colon.
      • The first character in a name can be followed by letters, numbers, hyphens, underscores, periods, or colons.
      • Names cannot begin with an XML letter combination.

    The XML document has the following structure:

    • The first line of the XML document is called declaration XML. This is an optional string that specifies the version of the XML standard (usually 1.0). The character encoding and external dependencies can also be specified here.
    • A comment can be placed anywhere in the tree. XML comments are placed inside a pair of . Two hyphens (--) cannot be used in any part within a comment.
    • The rest of this XML document consists of nested elements, some of which have attributes and content.
    • An element typically consists of opening and closing tags that wrap text and other elements.
    • The opening tag consists of the element name in angle brackets;
    • The closing tag consists of the same name in angle brackets, but a slash is added before the name.
    • The content of an element is everything between the opening and closing tags, including text and other (nested) elements.
    • In addition to content , an element can have attributes - name=value pairs added inside the opening tag after the element name.
    • Attribute values ​​are always quoted (single or double), the same attribute name cannot appear twice in the same element.
    • It is not recommended to use different types of quotes for attribute values ​​of the same tag.
    • To designate a element without content called an empty element, you must use a special notation consisting of a single tag, in which after the element name a forward slash "/" is placed.

    Unfortunately, the rules described above allow you to control only the formal correctness of the XML document, but not the content. To solve the second problem, the so-called schemes are used.

    The schema clearly defines the name and the structure of the root element, including specification of all its children. The programmer can specify which elements and how many are mandatory , and which are optional . The schema also determines which elements contain attributes , valid values ​​of these attributes, incl. default values ​​are .

    The following specifications are most commonly used to describe a circuit:

    • DTD ( Document Type Definition ) is the language for defining the type of documents.
    • XDR ( XML Data Reduced ) is an XML dialect developed by Microsoft.
    • XSD ( XML Schema Definition Language ) - recommended by the W3C.

    An XML document differs from an HTML document also in the way it is displayed in a web browser. Without CSS or XSL , the XML document is displayed as plain text in most web browsers. Some web browsers like Internet Explorer , Mozilla and Firefox display the document structure as a tree, allowing nodes to be collapsed and expanded with mouse clicks.


    Learn more

    • How long is a child with chickenpox contagious
    • Examples of fine motor skills in early childhood
    • Types of miscarriages in first trimester
    • What to give a vomiting child
    • What is fetal distress
    • How long after giving birth can i work out
    • How do you know if your miscarriage
    • How to make breast milk come in faster after birth
    • How can i take full custody of my child
    • Down's syndrome tests at 12 weeks
    • Signs of type 2 diabetes in kids

    Welcome

    Find us on iTunes!

    Visit The Masterpiece 's profile on Pinterest.

    Popular Posts

    • 10 Ways We Push Our Mom Friends Away
    • Your Kid, 10 Years Later
    • The Chill Mom’s Christmas Creed
    • Episode 30 – Minivans, the Mama Juggle, & a…
    • Episode 27 – Marriage, Motherhood, and Baby Hulks ///…
    • You’re Doing a Beautiful Thing {tribute to adoptive…

    © - The Masterpiece Mom

    Site Map