XML DOM: Replace Nodes
Let's see how to replace an element node with replaceChild()
, how to replace the data in a text node with replaceData()
and with nodeValue
property.
Replace an Element Node with replaceChild() Method
The replaceChild()
method replaces the specified node with the new node.
Syntax of replaceChild()
:
Node replaceChild(Node newChild, Node oldChild) throws DOMException
where:
- newChild is the new node to put in the child list.
- oldChild is the node being replaced in the list.
- This method returns the node replaced.
Example of replacing the first <book>
element with a new book:
xmlDoc = loadXMLDoc("/path/library.xml");
x = xmlDoc.documentElement;
//create a book element, title element and a text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A New Book");
//add the text node to the title node,
newTitle.appendChild(newText);
//add the title node to the book node
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0]
//replace the first book node with the new node
x.replaceChild(newNode,y);
Replace Data in a Text Node with replaceData() Method
The replaceData()
method is used to replace data in a text node.
void replaceData(offset, count, string) throws DOMException
The replaceData()
method has three parameters:
- offset is the offset from which to start replacing. Offset value starts at zero.
- length is the number of characters to replace.
- string is the string to insert.
Example: replace the eight first characters from the text node with "New String":
xmlDoc=loadXMLDoc("books.xml");
x = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"New String");
Replace Data in a Text Node with nodeValue Property
It is easier to replace data in a text node using the nodeValue
property.
Let's look at the same example as before but using the nodeValue
property:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
note
You can read more about changing node values in the Change Node chapter.