Use of Replace method in XML DOM
In this articles I am going to explain about replace an element and text node in XML DOM.
Replace method an Element Node
- The replaceChild() method replaces a node.
- The nodeValue property replaces text in a node.
Example
In this example, we replace an element:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="loadxmldoc.html">
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("library.xml");
a = xmlDoc.documentElement;
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("Notepad");
newTitle.appendChild(newText);
newNode.appendChild(newTitle);
b = xmlDoc.getElementsByTagName("book")[0]
a.replaceChild(newNode, y);
c = xmlDoc.getElementsByTagName("title");
for (i = 0; i < c.length; i++) {
document.write(c[i].childNodes[0].nodeValue);
document.write("<br />");
}
</script>
</body>
</html>
|
Define the code
- "loadxmldoc.html" get the data.
- First we create a new element node <boob>, <title> and a new text node "Notepad".
- We add a new text node to the new element node <title>.
- Then we replace first <book> element node with the new <book> element node.
Replace data in a Text Node
The replaceData() method is used to replace data in a text node.
There are three parameters use in replaceData() method:
- string: we insert a string.
- offset: Start at zero for replace character.
- length: replace the length of characters.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="loadxmldoc.html">
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("library.xml");
a = xmlDoc.getElementsByTagName("title")[0].childNodes[0];
document.write(a.nodeValue);
a.replaceData(0, 6, "Some");
document.write("<br />");
document.write(a.nodeValue);
</script>
</body>
</html>
|
Define the code
- "loadxmldoc.html" get the data.
- We add a new text node to the new element node <title>.
- Use the replaceData method to replace the six first characters from the text node with "Some".
You may also want to read these related articles :
Ask Your Question
Got a programming related question? You may want to post your question here
Programming Answers here