XML DOM Get node value


The nodeValue property is used to get the text value of a node.

The getAttribute() method returns the value of an attribute.


Get the value of an element

In the DOM, every component is a node. Element nodes have no text value.

The text of an element node is stored in a child node. This node is called a text node.

The way to get an element's text is to get the value of this child node (the text node).


Get element value

The getElementsByTagName() method returns a node list containing all elements with the specified tag name, in the order in which they appear in the source document.

The following code, by usingloadXMLDoc()holdbooks.xmlLoad into xmlDoc and retrieve the first <title> element:

xmlDoc=loadXMLDoc("books.xml");

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

The childNodes property returns a list of child nodes. The <title> element has only one child node. It is a text node.

The following code retrieves the text node of the <title> element:

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

The nodeValue property returns the text value of a text node:

Example

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

Try it Yourself »

Result: txt = "Everyday Italian"

Loop through all <title> elements:Try it Yourself


Get the value of an attribute

In the DOM, attributes are also nodes. Unlike element nodes, attribute nodes have text values.

The way to get an attribute's value is to get its text value.

This can be done using the getAttribute() method or the nodeValue property of the attribute node.


Get attribute value - getAttribute()

The getAttribute() method returns an attribute.Value。

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

Example

xmlDoc=loadXMLDoc("books.xml");

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

Try it Yourself »

Result: txt = "en"

Example explanation:

  1. UsageloadXMLDoc()put "books.xml" Load into xmlDoc
  2. Set the txt variable to the value of the "lang" attribute of the first title element node.

Loop through all <book> elements and get their "category" attributes:Try it Yourself


Get Attribute Value - getAttributeNode()

The getAttributeNode() method returns an attribute.node。

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

Example

xmlDoc=loadXMLDoc("books.xml");

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

Try it Yourself »

Result: Result: txt = "en"

Example explanation:

  1. UsageloadXMLDoc()put "books.xml" Load into xmlDoc
  2. Get the "lang" attribute node of the first <title> element node.
  3. Set the txt variable to the value of the attribute.

Loop through all <book> elements and get their "category" attributes:Try it Yourself


other extensions