Xml解析器/从XML节点列表创建XML DOM Document

时间:2012-05-12 15:12:59

标签: javascript dom

我正在努力寻找如何在JavaScript中构建一个全新的DOM文档,将其添加并从我已有的DOM节点列表中加载它。我发现的只是愚蠢的循环方式,但我非常确定这样的架构有一个合适的API。但我找不到一个!

1 个答案:

答案 0 :(得分:-1)

尝试这样的事情:

// Define a base XML document.
var xmlString = "<root>" +
    "<node id='1'>One</node>" +
    "<node id='2'>Two</node>" +
    "<node id='3'>Three</node>" +
    "<node id='4'>Four</node>" +
    "</root>";

// Use jQuery to parse it to a DOM document in a cross-browser fashion.
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​var xmlDoc = $.parseXML(xmlString);

// Grab some elements that we will write to a new document.
var node1 = xmlDoc.getElementById("1");
var node3 = xmlDoc.getElementById("3");

// Use jQuery to create the new document, then get a reference
// to the root element.
var newXmlDoc = $.parseXML("<newRoot></newRoot>");
var newRoot = newXmlDoc.getElementsByTagName("newRoot")[0];

// Clone the two elements into the new document.
newRoot.appendChild(node1.cloneNode(true));
newRoot.appendChild(node3.cloneNode(true));

// This will write out the text content of the two nodes
// we have cloned into the new document.
// Should write: "OneThree".
document.write(newXmlDoc.documentElement.textContent);

这是在jsFiddle中运行的代码:http://jsfiddle.net/sajaraki/JnSzK/

它结合使用JavaScript XML DOM实现和jQuery来解决加载和创建XML文档所涉及的浏览器不兼容问题。