在DOM中,你可以使用JavaScript来创建新的XML节点。以下是一个简单的例子,演示如何创建新的XML节点并将其添加到文档中:
// 创建一个 XMLHttpRequest 对象(用于获取 XML 文档)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // 当 XML 文档加载完成时执行的回调函数
    createXmlNode(this);
  }
};
// 打开并发送请求
xhttp.open("GET", "your_xml_file.xml", true);
xhttp.send();

// 创建 XML 节点并添加到文档
function createXmlNode(xml) {
  var xmlDoc = xml.responseXML;

  // 创建新的元素节点
  var newElement = xmlDoc.createElement("newElement");

  // 创建新的文本节点
  var newText = xmlDoc.createTextNode("This is the text content of the new element");

  // 将文本节点添加到元素节点中
  newElement.appendChild(newText);

  // 获取要添加新节点的父节点
  var parent = xmlDoc.getElementsByTagName("root")[0];

  // 将新节点添加到文档中
  parent.appendChild(newElement);

  // 输出添加新节点后的 XML 内容
  var xmlString = new XMLSerializer().serializeToString(xmlDoc);
  console.log(xmlString);

  // 保存更改(如果需要)
  // 可以将 xmlString 发送到服务器或以其他方式进行处理
}

在这个例子中,首先使用createElement创建一个名为"newElement"的新元素节点,然后使用createTextNode创建一个文本节点,设置其文本内容。接着,将文本节点添加到元素节点中,最后找到要添加新节点的父节点,使用appendChild将新节点添加到文档中。

最后,如果需要将更改保存回XML文档,可以使用XMLSerializer将修改后的文档序列化为字符串,然后进行相应的处理。在实际应用中,你可能需要将更改的文档发送到服务器或以其他方式进行处理。


转载请注明出处:http://www.zyzy.cn/article/detail/14572/XML DOM