XML DOM 教學課程登入
XML DOM 教學課程
作者:php.cn  更新時間:2022-04-13 15:27:56

DOM 替換節點


XML DOM 取代節點


replaceChild() 方法取代指定節點。

nodeValue 屬性取代文字節點中的文字。


tryitimg.gif 試試看- 實例


#下面的實例使用XML 檔案books .xml。
函數 loadXMLDoc(),位於外部 JavaScript 中,用於載入 XML 檔案。

取代元素節點
本範例使用 replaceChild() 來取代第一個 <book> 節點。

取代文字節點中的資料
本例使用 nodeValue 屬性來取代文字節點中的資料。


取代元素節點

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>

執行實例»

點擊"運行實例" 按鈕查看線上實例

實例解釋:

  1. #使用loadXMLDoc() 把"books.xml" 載入xmlDoc 中

  2. 建立一個新的元素節點<book>

  3. 建立一個新的元素節點<title>

  4. 建立一個新的文字節點,帶有文字"A Notebook"

  5. #向新元素節點<title> 追加這個新文字節點

  6. 向新元素節點<book> 追加這個新元素節點<title>

  7. 把第一個<book> 元素節點替換為新的<book> 元素節點


取代文字節點中的資料

replaceData() 方法用來取代文字節點中的資料。

replaceData() 方法有三個參數:

  • offset - 在何處開始替換字元。 offset 值以 0 開始。

  • length - 要取代多少字元

  • string - 要插入的字串

實例

<!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.replaceData(0,8,"Easy");

document.write("<br>");
document.write(x.nodeValue);

</script>
</body>
</html>

運行實例»

點擊"運行實例"按鈕查看線上實例

實例解釋:

  1. 使用loadXMLDoc() 把"books.xml" 載入xmlDoc

  2. 取得第一個< title> 元素節點的文字節點

  3. 使用replaceData 方法把文字節點的前8 個字元替換為"Easy"


使用nodeValue 屬性取代

用nodeValue 屬性取代文字節點中資料會更容易。

下面的程式碼片段將以"Easy Italian" 取代第一個<title> 元素中的文字節點值:

實例

<!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>

運行實例»

點擊"運行實例"按鈕查看線上實例

#實例解釋:

  1. 使用loadXMLDoc() 把"books.xml" 載入xmlDoc 中

  2. #取得第一個<title> 元素節點的文字節點


#######################################################################使用nodeValue 屬性來更改這個文字節點的文字############您可以在改變節點這一章中閱讀更多關於更改節點值的內容。 ############

PHP中文網