February 5, 2002 - Adding An Attribute Node to An XML Tree
February 5, 2002 Adding An Attribute Node to An XML Tree Tips: February 2002
Yehuda Shiran, Ph.D.
|
addNode()
function below creates a node of type "attribute"
:
function addNode() {
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
var MyNode;
var namedNodeMap;
xmlDoc.async = false;
xmlDoc.load("mydvd.xml");
alert(xmlDoc.documentElement.xml);
MyNode = xmlDoc.createNode("attribute", "Year", "");
namedNodeMap = xmlDoc.documentElement.childNodes.item(0).attributes;
namedNodeMap.setNamedItem(MyNode);
alert(xmlDoc.documentElement.xml);
}
The node is an object. Let's add it to our mydvd
tree, to the root's first child node. The root of the tree is <sales>
. Its first child node, (see the tree representation in Column 101's Page 2), is <summary>
. You usually start navigating the tree from the root. The root of the tree is:
xmlDoc.documentElement;
The collection of the root's childNodes
is:
xmlDoc.documentElement.childNodes
The first item on this collection is the first child:
xmlDoc.documentElement.childNodes.item(0)
The collection of attributes of this node (<summary>
) is:
xmlDoc.documentElement.childNodes.item(0).attributes
To insert the new node to this collection, you use the setNamedItem()
method, with the new node object as a parameter:
xmlDoc.documentElement.childNodes.item(0).attributes.setNamedItem(MyNode)
Try it now. The first alert box echoes the XML file before adding the attribute node. The second alert box reflects the addition. Notice the Year
attribute within the <summary>
tag.