Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Advanced XML DOM

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 The text value of the element:</p> <h2>Example</h2> <p>txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;</p> <p>Try it »</p> <hr /> <h2>Get the Attribute's Value</h2> <p>The following example retrieves the first <title> The text value of the element's "lang" attribute:</p> <h2>Example</h2> <p>txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");</p> <p>Try it »</p> <hr /> <h2>Changes the value of the element</h2> <p>The following example changes the first <title> The text value of the element:</p> <h2>Example</h2> <p>x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];</p> <p>x.nodeValue="Easy Cooking";</p> <p>Try it »</p> <hr /> <h2>Create a new attribute</h2> <p>The XML DOM setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute.</p> <p>The following example creates a new attribute (edition="first") and then adds it to every element:

Example

x=xmlDoc.getElementsByTagName("book");

for(i=0;i

{

x[i].setAttribute("edition","first");

}

Try it »


Creating Elements

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 ( ) with the text: First, and then adds it to the first element:

Example

newel=xmlDoc.createElement("edition");

newtext=xmlDoc.createTextNode("First");

newel.appendChild(newtext);

x=xmlDoc.getElementsByTagName("book");

x[0].appendChild(newel);

Try it »

Example Explanation


Delete elements

The following example deletes the first node of the first element:

Example

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.