XML DOM 創建節點

創建新的元素節點

createElement() 方法創建新的元素節點:

例子 1

newElement = xmlDoc.createElement("edition");
xmlDoc.getElementsByTagName("book")[0].appendChild(newElement);

親自試一試

例子解釋:

  1. 假設 books.xml 已被加載到 xmlDoc
  2. 創建一個新的元素節點 <edition>
  3. 將這個元素節點追加到第一個 <book> 元素

例子 2

循環遍歷并向所有 <book> 元素添加一個元素:

for (i = 0; i < xLen; i++) { 
    newEle = xmlDoc.createElement("edition");
    newText = xmlDoc.createTextNode("第一版");
    newEle.appendChild(newText);
    x[i].appendChild(newEle);
}

親自試一試

創建新的屬性節點

createAttribute() 用于創建新的屬性節點:

例子 1

newAtt = xmlDoc.createAttribute("edition");
newAtt.nodeValue = "第一版";
xmlDoc.getElementsByTagName("title")[0].setAttributeNode(newAtt);

親自試一試

例子解釋:

  1. 假設 books.xml 被加載到 xmlDoc
  2. 創建新的屬性節點 "edition"
  3. 將這個屬性節點的值設置為 "first"
  4. 將這個新屬性節點添加到第一個 <title> 元素

例子 2

循環遍歷所有 <title> 元素并添加新的屬性節點:

for (i = 0; i < xLen; i++) { 
    newAtt = xmlDoc.createAttribute("edition");
    newAtt.value = "第一版";
    x[i].setAttributeNode(newAtt);
}

親自試一試

如果該屬性已存在,則將其替換為新屬性。

使用 setAttribute() 創建屬性

由于 setAttribute() 方法會在屬性不存在時創建新屬性,因此它也可用于創建新屬性。

例子 1

xmlDoc.getElementsByTagName('book')[0].setAttribute("edition","first");

親自試一試

例子解釋:

  1. 假設 books.xml 已被加載到 xmlDoc
  2. 將第一個 <book> 元素的 "edition" 屬性的值設置為 "first"

例子 2

循環遍歷所有 <title> 元素并添加新屬性:

for(i = 0; i < x.length; i++) {
    x[i].setAttribute("edition", "第一版");
}

親自試一試

創建文本節點

createTextNode() 方法創建新的文本節點:

例子 1

newEle = xmlDoc.createElement("edition");
newText = xmlDoc.createTextNode("first");
newEle.appendChild(newText);
xmlDoc.getElementsByTagName("book")[0].appendChild(newEle);

親自試一試

例子解釋:

  1. 假設 books.xml 已被加載到 xmlDoc
  2. 創建新的元素節點 <edition>
  3. 創建新的文本節點,其中包含文本 "first"
  4. 將這個新的文本節點追加到新的元素節點
  5. 將新元素節點追加到第一個 <book> 元素

例子 2

將帶有文本節點的元素節點添加到所有 <book> 元素:

for (i = 0; i < xLen; i++) { 
    newEle = xmlDoc.createElement("edition");
    newText = xmlDoc.createTextNode("第一版");
    newEle.appendChild(newText);
    x[i].appendChild(newEle);
}

親自試一試

創建 CDATA Section 節點

createCDATASection() 方法創建新的 CDATA section 節點。

例子 1

newCDATA = xmlDoc.createCDATASection("新年特惠 & 限時折扣");
xmlDoc.getElementsByTagName("book")[0].appendChild(newCDATA);

親自試一試

例子解釋:

  1. 假設 books.xml 已被加載到 xmlDoc
  2. 創建新的 CDATA section 節點
  3. 將這個新的 CDATA 節點追加到第一個 <book> 元素

例子 2

循環遍歷并向所有 <book> 元素添加 CDATA 部分:

x = xmlDoc.getElementsByTagName("book");
xLen = x.length;
newtext = "新年特惠 & 限時折扣";
for (i = 0; i < xLen; i++) { 
    newCDATA = xmlDoc.createCDATASection(newtext);
    x[i].appendChild(newCDATA);
}

親自試一試

創建注釋節點

createComment() 方法創建新的注釋節點。

例子 1

newComment = xmlDoc.createComment("2024 年 2 月修訂");
xmlDoc.getElementsByTagName("book")[0].appendChild(newComment);

親自試一試

例子解釋:

  1. 假設 books.xml 已被加載到 xmlDoc
  2. 創建新的注釋節點
  3. 將這個新的注釋節點追加到第一個 <book> 元素

例子 2

循環遍歷并向所有 <book> 元素添加注釋節點:

x = xmlDoc.getElementsByTagName("book");
xLen = x.length
for (i = 0; i < xLen; i++) { 
    newComment = xmlDoc.createComment("2024 年 2 月修訂");
    x[i].appendChild(newComment);
}

親自試一試