XML DOM – 替換節點
replaceChild() 方法替換指定節點。
nodeValue 屬性替換文本節點中的文本。
嘗試一下- 實例
下面的實例使用XML文件books.xml 。
函數loadXMLDoc() ,位於外部JavaScript中,用於加載XML文件。
替換元素節點
本例使用replaceChild() 來替換第一個<book> 節點。
替換文本節點中的數據
本例使用nodeValue 屬性來替換文本節點中的數據。
替換元素節點
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);
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);
嘗試一下»
實例解釋:
- 使用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 屬性來更改這個文本節點的文本
您可以在改變節點這一章中閱讀更多有關更改節點值的內容。