Xml Dom Advanced
# XML DOM Advanced
* * *
## XML DOM - Advanced
In earlier chapters of this tutorial, we introduced XML DOM and used the getElementsByTagName() method of XML DOM to retrieve data from an XML document.
In this chapter, we will explore some other important XML DOM methods.
You can learn more about XML DOM in our (
* * *
## Getting Element Values
The XML file used in the following example: [books.xml](
The following example retrieves the text value of the first element:
## Example
txt=xmlDoc.getElementsByTagName("title").childNodes.nodeValue;
[Try it yourself Β»](
* * *
## Getting Attribute Values
The following example retrieves the text value of the "lang" attribute of the first element:
## Example
txt=xmlDoc.getElementsByTagName("title").getAttribute("lang");
[Try it yourself Β»](
* * *
## Changing Element Values
The following example changes the text value of the first element:
## Example
x=xmlDoc.getElementsByTagName("title").childNodes;
x.nodeValue="Easy Cooking";
[Try it yourself Β»](
* * *
## Creating New Attributes
The setAttribute() method of XML DOM can be used to change an existing attribute value or create a new one.
The following example creates a new attribute (edition="first") and adds it to every element:
## Example
x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x.setAttribute("edition","first");
}
[Try it yourself Β»](
* * *
## Creating Elements
The createElement() method of XML DOM creates a new element node.
The createTextNode() method of XML DOM creates a new text node.
The appendChild() method of XML DOM adds a child node to a 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, then append the text node to the existing element node.
The following example demonstrates this process:
YouTip