Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XML DOM Advanced


May 27, 2021 XML


Table of contents


XML DOM Advanced


XML DOM - Advanced

Earlier in this tutorial, we covered XML DOM and used XML DOM's getElementsByTagName() method to get data back from XML documents.

In this chapter we'll combine some other important XML DOM methods.

You can learn more about XML DOM in our XML DOM tutorial.


Gets the value of the element

The XML file used in the following example: .xml.

The following example retrieves the text value of the first element:

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

Try it out . . .

Gets the value of the property

The following example retrieves the text value of the "lang" property of the first element:

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

Try it out . . .

Change the value of the element

The following example changes the text value of the first element:

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

Try it out . . .

Create a new property

XML DOM's setAttribute() method can be used to change an existing property value or create a new property.

The following example creates a new property (edition-"first") and then adds it to each element:

x=xmlDoc.getElementsByTagName("book");

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

Try it out . . .

Create an element

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

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

XML DOM's appendChild() method adds child nodes to the 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 the existing node.

The following example creates a new element with the following text: First, and then adds it to the first element:

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

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

Try it out . . .

The instance explanation

  • Create an element
  • Create a text node with a value of First
  • Add this text node to the new element
  • Append the element to the first

Delete the element

The following instance removes the first node of the first element:

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

Try it out . . .

Note: The results of the above instance may vary depending on the browser used. F irefox treats new line characters as empty text nodes, which is not the case with Internet Explorer. You can read more about this problem and how to avoid it in our XML DOM tutorial.