XML DOM Node Information

Node attributes: nodeName, nodeValue, and nodeType.

Example

The following examples use an XML file books.xml.

function loadXMLDoc(), located in external JavaScript, used to load XML files.

Get the node name of an element node
This example uses the nodeName attribute to get the node name of the root element in "books.xml".
Get text from a text node
This example uses the nodeValue attribute to get the text of the first <title> element in "books.xml".
Change the text in a text node
This example uses the nodeValue attribute to change the text of the first <title> element in "books.xml".
Get the node name and type of an element node
This example uses the nodeName and nodeType attributes to get the node name and type of the root element in "books.xml".

node attributes

In the XML Document Object Model (DOM), each node is aObject.

Objects have methods (functions) and properties (information about the object), and can be accessed and manipulated through JavaScript.

The three important XML DOM node attributes are:

  • nodeName
  • nodeValue
  • nodeType

nodeValue attribute

The nodeName attribute specifies the name of the node.

  • nodeName is read-only
  • The nodeName of the element node is the same as the tag name
  • The nodeName of the attribute node is the name of the attribute
  • The nodeName of the text node is always #text
  • The nodeName of the document node is always #document

TIY

nodeValue attribute

The nodeValue attribute specifies the value of the node.

  • The nodeValue of the element node is undefined
  • The nodeValue of the text node is the text itself
  • The nodeValue of the attribute node is the value of the attribute

Example 1: Get the value of the element

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

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

Result: txt = "Harry Potter"

Code explanation:

  • Load "books.xml" into xmlDoc using loadXMLDoc()
  • Get the text node of the first <title> element node
  • Set the txt variable to the value of the text node

TIY

Example 2: Change the value of the element

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

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

Code explanation:

  • Load "books.xml" into xmlDoc using loadXMLDoc()
  • Get the text node of the first <title> element node
  • Change the value of the text node to "Easy Cooking"

TIY

nodeType attribute

The nodeType attribute specifies the type of the node.

nodeType is read-only.

The most important node type is:

Element type Node type
Elements 1
Attributes 2
Text 3
Comments 8
Document 9

TIY