Advanced XML DOM
XML DOM - Advanced
inIn an earlier chapter of this tutorial, we introduced the XML DOM and used the XML DOM getElementsByTagName() method to retrieve data from an XML document.
In this chapter, we will combine several other important XML DOM methods.
You can find it in our XML DOM Tutorial to learn more about the XML DOM.
Get the Value of an Element
The XML file used in the example below:books.xml。
The following example retrieves the first
Example
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
Try it »
Get the Attribute's Value
The following example retrieves the first
Example
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
Try it »
Changes the value of the element
The following example changes the first
Example
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
Try it »
Create a new attribute
The XML DOM setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute.
The following example creates a new attribute (edition="first") and then adds it to every
Example
x=xmlDoc.getElementsByTagName("book");
for(i=0;i { x[i].setAttribute("edition","first"); } Try it » 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 a node (after the last child node). To create a new element with text content, you need to create both a new element node and a new text node, and then append them to an existing node. The following example creates a new element (
newel=xmlDoc.createElement("edition"); newtext=xmlDoc.createTextNode("First"); newel.appendChild(newtext); x=xmlDoc.getElementsByTagName("book"); x[0].appendChild(newel); Try it » Example Explanation The following example deletes the first node of the first x=xmlDoc.getElementsByTagName("book")[0]; x.removeChild(x.childNodes[0]); Try it » **Note:** The result of the example above may vary depending on the browser used. Firefox treats new-line characters as empty text nodes, while Internet Explorer does not. You can read more about this and how to avoid it in our XML DOM Tutorial tutorial.
Creating Elements
Example
Delete elements
Example