replaceChild() 方法替换指定节点。
nodeValue 属性替换文本节点中的文本。
下面的实例使用 XML 文件 books.xml。
函数 loadXMLDoc(),位于外部 JavaScript 中,用于加载 XML 文件。
替换元素节点
本例使用 replaceChild() 来替换第一个 <book> 节点。
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.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 Notebook");
//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);
z=xmlDoc.getElementsByTagName("title");
for (i=0;i<z.length;i++)
{
document.write(z[i].childNodes[0].nodeValue);
document.write("<br>");
}
</script>
</body>
</html>替换文本节点中的数据
本例使用 nodeValue 属性来替换文本节点中的数据。
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js">
</script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
document.write(x.nodeValue);
x.nodeValue="Easy Italian";
document.write("<br>");
document.write(x.nodeValue);
</script>
</body>
</html>replaceChild() 方法用于替换节点。
下面的代码片段替换第一个 <book> 元素:
xmlDoc=loadXMLDoc("books.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 Notebook");
//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);
实例解释:
replaceData() 方法用于替换文本节点中的数据。
replaceData() 方法有三个参数:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
实例解释:
用 nodeValue 属性来替换文本节点中数据会更加容易。
下面的代码片段将用 "Easy Italian" 替换第一个 <title> 元素中的文本节点值:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
实例解释:
您可以在改变节点这一章中阅读更多有关更改节点值的内容。