XML DOM - add nodes
Try - Example
The following example uses XML files the Books.xml .
Function loadXMLDoc () , in an external JavaScript is used to load the XML file.
After the last child node to add a node
This example uses appendChild () method adds a child node to an existing node.
Before specified child node to add a node
This example uses insertBefore () method before a specified child node into a node.
Adding a new property
This example uses the setAttribute () method to add a new property.
Add data to a text node
This example uses insertData () insert data into an existing text node.
Add a Node - appendChild ()
appendChild () method adds a child node to an existing node.
The new node is added (appended) to any existing child node after.
Note: If theposition of the node is very important, please use the insertBefore () method.
The following code fragment creates an element (<edition>), and add it after the last child node of the first <book> element:
Examples
newel=xmlDoc.createElement("edition");
x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Create a new node <edition>
- Append the node to the first <book> element
Traversal to all <book> element append an element: try
Insert node - insertBefore ()
insertBefore () method is used before the specified child node into the node.
The position is very important to add a node, this method is useful:
Examples
newNode=xmlDoc.createElement("book");
x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book")[3];
x.insertBefore(newNode,y);
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- Creates a new element node <book>
- The new node is inserted before the last <book> element node
If insertBefore () The second parameter is null, the new node will be added after the last existing child node.
x.insertBefore (newNode, null) and x.appendChild (newNode)can append a new child node to x.
Add New Attribute
addAtribute () This method does not exist.
If the property does not exist, the setAttribute () to create a new property:
Examples
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("edition","first");
try it"
Examples explain:
- Use loadXMLDoc () to " the Books.xml " into xmlDoc
- The "edition" attribute value is set to the first <book> element (created) for the "first"
Note: If theproperty already exists, setAttribute () method will overwrite the existing value.
Adding text node text - insertData ()
insertData () method to insert data into an existing text node.
insertData () method takes two arguments:
- offset - Where to begin inserting characters (beginning with 0)
- string - the string to insert
The following code fragment will "Easy" added to XML loaded first <title> element of the text node:
Examples
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.insertData(0,"Easy ");
try it"