Advanced XML DOM
XML DOM - Advanced
In the earlier chapters of this tutorial , we introduced the XML DOM, and uses the XML DOM getElementsByTagName () method to retrieve data from XML documents.
In this chapter we will combine a number of other important XML DOM methods.
You can in our XML DOM tutorial to learn more about the XML DOM knowledge.
Gets the value of the element
XML files used in the following examples: the Books.xml .
The following example retrieves the first text value of the <title> element:
Examples
Gets the value of the property
The following example retrieves the text value of the first <title> element of the "lang" attribute:
Examples
Change the value of the element
The following example changes the first text value <title> element:
Examples
x.nodeValue="Easy Cooking";
Create a new property
The XML DOM setAttribute () method can be used to change the existing property value, or create a new property.
The following example creates a new attribute (edition = "first"), and then add it to each <book> element:
Examples
for(i=0;i<x.length;i++)
{
x[i].setAttribute("edition","first");
}
Create element
The XML DOM createElement () method creates a new element node.
The XML DOM createTextNode () method creates a new text node.
The XML DOM appendChild () method adds a child node to node (after the last child node).
To create a new element with text content, you need to create a new element node element and a new text node, and then he added to the existing nodes.
The following example creates a new element (<edition>), with the following text: First, and then add it to the first <book> element:
Examples
newtext=xmlDoc.createTextNode("First");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book");
x[0].appendChild(newel);
Examples explained
- Create a <edition> element
- Creating value "First" text node
- Append the text node to the new <edition> element
- The <edition> element is added to the first <book> element
Removing elements
The following example remove the first <book> element of the first node:
Examples
x.removeChild(x.childNodes[0]);
NOTE: The above examples may result depending on the browser and different.Firefox treats new lines as empty text nodes, Internet Explorer is not the case. You can in our XML DOM tutorial in reading more about this problem and how to avoid it.