XML DOM Getting Node Values
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 do not have a 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 the Element's 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 uses loadXMLDoc() Puts the books.xml to load into xmlDoc and retrieve the first
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
The childNodes property returns a list of child nodes.
The following code retrieves
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 »
Result: txt = "Everyday Italian"
Traverse all
Get the Attribute's Value
In the DOM, attributes are also nodes. Unlike element nodes, attribute nodes have a text value.
The way to get an attribute's value is to get its text value.
This can be done by using the getAttribute() method or the nodeValue property of the attribute node.
Getting an Attribute Value - getAttribute()
The getAttribute() method returns the attributeValue.
The following code retrieves the first
Example
xmlDoc=loadXMLDoc("books.xml");
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
Try it »
Result: txt = "en"
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Set the txt variable to the value of the "lang" attribute of the first title element node
Iterate over all the
Getting an Attribute Value - getAttributeNode()
The getAttributeNode() method returns the attributeNode.
The following code retrieves the first
Example
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt=x.nodeValue;
Try it »
Result: Result: txt = "en"
Example explanation:
- Use loadXMLDoc() to load "books.xml" load into xmlDoc
- Get the first
element node's "lang" attribute node
Iterate over all the