XML DOM Create Nodes
Examples
In the examples below, we will use the XML file
books.xml, and the JavaScript function
loadXMLDoc().
Create an
element node
This example uses createElement() to create a new element node, and appendChild() to
add it to a node list.
Create an attribute
node
This example uses createAttribute() to create a new attribute node, and
setAttributeNode() to insert it to an element.
Create a
text node
This example uses createTextNode() to create a new text node, and appendChild() to
add it to a node list.
Create a CDATA section node
This example uses createCDATAsection() to create a CDATA section node, and
appendChild() to add it to a node list.
Create a
comment node
This example uses createComment() to create a comment node, and appendChild() to
add it to a node list.
Create an Element
The createElement() method creates a new element node.
The following code fragment creates an element (<edition>), and adds it
after the last child of each
<book> element:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newel
for (i=0;i<x.length;i++)
{
newel=xmlDoc.createElement('edition');
x[i].appendChild(newel);
}
|
Create an Attribute
The createAttribute() creates a new attribute node.
The following code fragment creates an "edition" attribute and adds it to
all <book> elements:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newatt;
for (i=0;i<x.length;i++)
{
newatt=xmlDoc.createAttribute("edition");
newatt.value="first";
x[i].setAttributeNode(newatt);
}
|
Create a Text Node
The createTextNode() method creates a new text node.
The following code fragment creates an element (<edition>), with a text
node ('First') in it, and adds it after the last child of each
<book> element:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newel,newtext
for (i=0;i<x.length;i++)
{
newel=xmlDoc.createElement('edition');
newtext=xmlDoc.createTextNode('First');
newel.appendChild(newtext);
x[i].appendChild(newel);
}
|
Create a CDATA Section Node
The createCDATASection() method creates a new CDATA section node.
The following code fragment creates a CDATA section, and adds it after the
last child of each <book> element:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newCDATA,newtext;
newtext="Special Offer & Book Sale";
for (i=0;i<x.length;i++)
{
newCDATA=xmlDoc.createCDATASection(newtext);
x[i].appendChild(newCDATA);
}
|
Create a Comment Node
The createComment() method creates a new comment node.
The following code fragment creates a comment node, and adds it after the
last child of each <book> element:
xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newComment,newtext;
newtext="Revised September 2006";
for (i=0;i<x.length;i++)
{
newComment=xmlDoc.createComment(newtext);
x[i].appendChild(newComment);
}
|
|