XML DOM 替換節點
replaceChild() 方法替換指定節點。
nodeValue 屬性替換文本節點中的文本。

嘗試一下 - 實例
下麵的實例使用 XML 檔 books.xml。
函數 loadXMLDoc(),位於外部 JavaScript 中,用於加載 XML 檔。
本例使用 replaceChild() 來替換第一個 <book> 節點。
本例使用 nodeValue 屬性來替換文本節點中的數據。
替換元素節點
replaceChild() 方法用於替換節點。
下麵的代碼片段替換第一個 <book> 元素:
實例
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement;
// 創建新的 book 元素, title 元素及 node 節點
newNode=xmlDoc.createElement("book");
newTitle=xmlDoc.createElement("title");
newText=xmlDoc.createTextNode("A Notebook");
// 將 text 節點添加到 title 節點中
newTitle.appendChild(newText);
// 將 title 節點添加到 book 節點中
newNode.appendChild(newTitle);
y=xmlDoc.getElementsByTagName("book")[0]
// 使用新節點替換第一個 book 節點
x.replaceChild(newNode,y);
實例解釋:
- 使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
- 創建一個新的元素節點 <book>
- 創建一個新的元素節點 <title>
- 創建一個新的文本節點,帶有文本 "A Notebook"
- 向新元素節點 <title> 追加這個新文本節點
- 向新元素節點 <book> 追加這個新元素節點 <title>
- 把第一個 <book> 元素節點替換為新的 <book> 元素節點
替換文本節點中的數據
replaceData() 方法用於替換文本節點中的數據。
replaceData() 方法有三個參數:
- offset - 在何處開始替換字元。offset 值以 0 開始。
- length - 要替換多少字元
- string - 要插入的字串
實例
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.replaceData(0,8,"Easy");
實例解釋:
- 使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
- 獲取第一個 <title> 元素節點的文本節點
- 使用 replaceData 方法把文本節點的前 8 個字元替換為 "Easy"
使用 nodeValue 屬性代替
用 nodeValue 屬性來替換文本節點中數據會更加容易。
下麵的代碼片段將用 "Easy Italian" 替換第一個 <title> 元素中的文本節點值:
實例
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Italian";
實例解釋:
- 使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
- 獲取第一個 <title> 元素節點的文本節點
- 使用 nodeValue 屬性來更改這個文本節點的文本
您可以在改變節點這一章中閱讀更多有關更改節點值的內容。