XML DOM Advanced


XML DOM - Advanced

InIn the earlier chapters of this tutorialwe introduced the XML DOM and used the XML DOM's getElementsByTagName() method to retrieve data from an XML document.

In this chapter, we will look at some other important XML DOM methods.

You can, in ourXML DOM Tutoriallearn more about XML DOM.


Get the Value of an Element

The XML file used in the examples below:books.xml。

The following example retrieves the text value of the first <title> element:

Example

txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

Try it Yourself »


Get the Value of an Attribute

The following example retrieves the text value of the "lang" attribute of the first <title> element:

Example

txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");

Try it Yourself »


Change the Value of an Element

The following example changes the text value of the first <title> element:

Example

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";

Try it Yourself »


Create a New Attribute

The XML DOM's 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 each <book> element:

Example

x=xmlDoc.getElementsByTagName("book");

for(i=0;i<x.length;i++)
{
x[i].setAttribute("edition","first");
}

Try it Yourself »


Create an Element

The XML DOM's createElement() method creates a new element node.

The XML DOM's createTextNode() method creates a new text node.

The XML DOM's 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 it to an existing node.

The following example creates a new element (<edition>) with the following text: First, and then adds it to the first <book> element:

Example

newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("First");
newel.appendChild(newtext);

x=xmlDoc.getElementsByTagName("book");
x[0].appendChild(newel);

Try it Yourself »

Example explained

  • Create an <edition> element
  • Create a text node with the value "First"
  • Append this text node to the new <edition> element
  • Append the <edition> element to the first <book> element

Delete an Element

The following example deletes the first node of the first <book> element:

Example

x=xmlDoc.getElementsByTagName("book")[0];
x.removeChild(x.childNodes[0]);

Try it Yourself »

Note:The result of the above example may vary depending on the browser used. Firefox treats newline characters as empty text nodes, while Internet Explorer does not. You can, in ourXML DOM Tutorialread more about this problem and how to avoid it.

Other Extensions