XML DOM Get Node Values

To get the text value of a node, we can use the nodeValue property and to get the value of an attribute, we can use the getAttribute() method.

Get the Value of an Element:

Everything is a node in the DOM. There is no text value in the element nodes, but is stored in a child node, also called a text node. The value of the elements’ text node must be retrieved to retrieve the text value of an element.

The getElementsByTagName Method:

A node list of all elements, with the specified tag name, is returned by the getElementsByTagName() method in the same order as they appear in the source document.

Example:

var x = xmlDoc.getElementsByTagName("title")[0];

Explanation:

Here, “books.xml” has been loaded into xmlDoc and we are retrieving its first <title> element.

The ChildNodes Property:

To return a list of an element’s child nodes the childNodes property is used.

Example: To retrieve the text node of the first <title> element:

x = xmlDoc.getElementsByTagName("title")[0];
y = x.childNodes[0];

The nodeValue Property:

To return the text value of a text node, the nodeValue property is used.

Example: To retrieve the text value of the text node of the first <title> element:

x = xmlDoc.getElementsByTagName("title")[0];
y = x.childNodes[0];
z = y.nodeValue;

Example:





Output:

Example: Looping through all the <title> elements:





Output:

Get the Value of an Attribute:

Attributes in the DOM are nodes. But, attribute nodes have text values and are not like element nodes. We need to get the text value of an attribute to get the value of an attribute. For this, the getAttribute() method or the nodeValue property of the attribute node can be used.

Get an Attribute Value – getAttribute():

To get an attribute’s value, the getAttribute() method is used.

Example:

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

Explanation:

In the above example, we are retrieving the text value of the “lang” attribute of the first <title> element.

Example: Looping through all the elements:





Explanation:

In the above example, we are looping through all the <book> elements and are retrieving their “category” attributes.

Get an Attribute Value – getAttributeNode():

To get an attribute node, the getAttributeNode() method is used.

Example:

Output:

Explanation:

In the above example, we are retrieving the text value of the “lang” attribute of the first <title> element.

Example: Looping through all the elements:





Explanation:

In the above example, we are looping through all the <book> elements and are retrieving their “category” attributes.

Please follow and like us:
Content Protection by DMCA.com