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

DOM 新增節點


XML DOM 新增節點


tryitimg.gif 試試看- 實例


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

在最後一個子節點之後新增一個節點
本例使用 appendChild() 方法在一個現有的節點中新增一個子節點。

在指定的子節點之前新增一個節點
本例使用 insertBefore() 方法在一個指定的子節點之前插入一個節點。

新增一個新屬性
本例使用 setAttribute() 方法新增一個新的屬性。

新增資料在文字節點
本例使用 insertData() 把資料插入一個已有的文字節點。


新增節點 - appendChild()

appendChild() 方法新增一個子節點到一個現有的節點。

新節點會加入(追加)到任何已有的子節點之後。

注意:如果節點的位置很重要,請使用 insertBefore() 方法。

下面的程式碼片段建立一個元素(<edition>),並把它加到第一個<book> 元素的最後一個子節點後面:

##實例

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

newel=xmlDoc.createElement("edition");

x=xmlDoc.getElementsByTagName("book")[0];
x.appendChild(newel);

document.write(x.getElementsByTagName("edition")[0].nodeName);
</script>
</body>
</html>

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

實例解釋:

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

  2. 建立一個新節點<edition>

  3. #把這個節點追加到第一個<book> 元素

#遍歷並向所有<book> 元素追加一個元素:試試



############################ ###插入節點- insertBefore()######insertBefore()方法用於在指定的子節點之前插入節點。 ######在被新增的節點的位置很重要時,此方法很有用:#########實例######
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

newNode=xmlDoc.createElement("book");

x=xmlDoc.documentElement;
y=xmlDoc.getElementsByTagName("book");

document.write("Book elements before: " + y.length);
document.write("<br>");
x.insertBefore(newNode,y[3]);

y=xmlDoc.getElementsByTagName("book");
document.write("Book elements after: " + y.length);
</script>
</body>
</html>
#########執行實例»######點擊"運行實例" 按鈕查看線上實例#######

實例解釋:

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

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

  3. 把這個新節點插到最後一個<book> 元素節點之前

##如果insertBefore() 的第二個參數是null,新節點將被加入最後一個已有的子節點之後。

x.insertBefore(newNode,null)x.appendChild(newNode) 都可以向 x 追加一個新的子節點。


新增屬性

addAtribute() 這個方法是不存在的。

如果屬性不存在,則setAttribute() 可建立一個新的屬性:

實例

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"> 
</script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");

x[0].setAttribute("edition","first");

document.write("Edition: ");
document.write(x[0].getAttribute("edition"));

</script>
</body>
</html>
##運行實例»
點擊"運行實例" 按鈕查看線上實例

實例解釋:

    使用loadXMLDoc() 把"books.xml"載入xmlDoc 中
  1. 把第一個<book> 元素的"edition" 屬性的值設定(建立)為"first"
#注意:

如果屬性已存在,setAttribute() 方法將覆寫已有的值。

為文字節點新增文字 - insertData()

insertData() 方法將資料插入已有的文字節點中。

insertData() 方法有兩個參數:

    offset - 在何處開始插入字元(以0 開始)
  • string - 要插入的字串
  • 下面的程式碼片段將把"Easy" 加入到已載入的XML 的第一個<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.insertData(0,"Easy ");
document.write("<br>");
document.write(x.nodeValue);

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

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