2016
10-20

DOM 替換節(jié)點(diǎn)

清華大佬耗費(fèi)三個(gè)月吐血整理的幾百G的資源,免費(fèi)分享!....>>>

XML DOM 替換節(jié)點(diǎn)


replaceChild() 方法替換指定節(jié)點(diǎn)。

nodeValue 屬性替換文本節(jié)點(diǎn)中的文本。


實(shí)例

嘗試一下 - 實(shí)例

下面的實(shí)例使用 XML 文件 books.xml。
函數(shù) loadXMLDoc(),位于外部 JavaScript 中,用于加載 XML 文件。

替換元素節(jié)點(diǎn)
本例使用 replaceChild() 來(lái)替換第一個(gè) <book> 節(jié)點(diǎn)。

替換文本節(jié)點(diǎn)中的數(shù)據(jù)
本例使用 nodeValue 屬性來(lái)替換文本節(jié)點(diǎn)中的數(shù)據(jù)。


替換元素節(jié)點(diǎn)

replaceChild() 方法用于替換節(jié)點(diǎn)。

下面的代碼片段替換第一個(gè) <book> 元素:

實(shí)例

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);

實(shí)例解釋:

  1. 使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
  2. 創(chuàng)建一個(gè)新的元素節(jié)點(diǎn) <book>
  3. 創(chuàng)建一個(gè)新的元素節(jié)點(diǎn) <title>
  4. 創(chuàng)建一個(gè)新的文本節(jié)點(diǎn),帶有文本 "A Notebook"
  5. 向新元素節(jié)點(diǎn) <title> 追加這個(gè)新文本節(jié)點(diǎn)
  6. 向新元素節(jié)點(diǎn) <book> 追加這個(gè)新元素節(jié)點(diǎn) <title>
  7. 把第一個(gè) <book> 元素節(jié)點(diǎn)替換為新的 <book> 元素節(jié)點(diǎn)

替換文本節(jié)點(diǎn)中的數(shù)據(jù)

replaceData() 方法用于替換文本節(jié)點(diǎn)中的數(shù)據(jù)。

replaceData() 方法有三個(gè)參數(shù):

  • offset - 在何處開(kāi)始替換字符。offset 值以 0 開(kāi)始。
  • length - 要替換多少字符
  • string - 要插入的字符串

實(shí)例

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.replaceData(0,8,"Easy");

實(shí)例解釋:

  1. 使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
  2. 獲取第一個(gè) <title> 元素節(jié)點(diǎn)的文本節(jié)點(diǎn)
  3. 使用 replaceData 方法把文本節(jié)點(diǎn)的前 8 個(gè)字符替換為 "Easy"

使用 nodeValue 屬性代替

用 nodeValue 屬性來(lái)替換文本節(jié)點(diǎn)中數(shù)據(jù)會(huì)更加容易。

下面的代碼片段將用 "Easy Italian" 替換第一個(gè) <title> 元素中的文本節(jié)點(diǎn)值:

實(shí)例

xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];

x.nodeValue="Easy Italian";

實(shí)例解釋:

  1. 使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
  2. 獲取第一個(gè) <title> 元素節(jié)點(diǎn)的文本節(jié)點(diǎn)
  3. 使用 nodeValue 屬性來(lái)更改這個(gè)文本節(jié)點(diǎn)的文本

您可以在改變節(jié)點(diǎn)這一章中閱讀更多有關(guān)更改節(jié)點(diǎn)值的內(nèi)容。


掃碼二維碼 獲取免費(fèi)視頻學(xué)習(xí)資料

編程學(xué)習(xí)