如何使用jQuery / JavaScript合并XML对象

时间:2013-11-19 13:28:03

标签: javascript jquery xml xml-parsing merge

我想将不同XML文件的数据合并到一个大的XML树中。我的想法是将所有即将到来的节点附加到第一个XML文件的根节点。但是,在尝试调用“mergedXml.documentElement.appendChild”时,我收到“TypeError”。这是我的代码:

var mergedXml = undefined;

$.each(files, function(index, value) {
  $.ajax({
    url: value,
    cache: true,
    async: false,
    dataType: 'text',
    success: function(data) {
      var xmlDocument = $.parseXML(data);

      if (typeof mergedXml === 'undefined') {
        mergedXml = xmlDocument;
      } else {
        // New children
        var childNodes = xmlDocument.documentElement.childNodes;
        var children = childNodes.length;
        for (var i = 0; i < children; i++) {
          var node = childNodes[i];
          // How to append these nodes to the mergedXml root?
          // I tried:
          // mergedXml.documentElement.appendChild(node);
          // But then I get...
          // TypeError: Argument 1 of Node.appendChild is not an object. 
        }
      }
    }
  });
});

也许你可以帮助我?

1 个答案:

答案 0 :(得分:1)

我怀疑你得到的错误是由Node.appendChild从原始父节点中删除节点引起的,所以你试图访问不再存在的节点。我建议用for循环替换while循环:

var node;
while (xmlDocument.documentElement.hasChildNodes()) {
    node = xmlDocument.documentElement.childNodes[0];
    mergedXml.documentElement.appendChild(node); 
}

完整解决方案:

  var mergedXml = undefined;
  $.each(files, function(index, value) {
    $.ajax({
      url: value,
      cache: true,
      async: false,
      dataType: 'text',
      success: function(data) {
        var xmlDocument = $.parseXML(data);

        if (typeof mergedXml === 'undefined') {
          // Init XML collection
          mergedXml = xmlDocument;
        } else {
          // Add new children to XML collection
          var node;
          while (xmlDocument.documentElement.hasChildNodes()) {
            node = xmlDocument.documentElement.childNodes[0];
            mergedXml.documentElement.appendChild(node);
          }
        }

        if (index === files.length - 1) {
          console.log('Total nodes in root: ' + mergedXml.documentElement.childNodes.length);
        }
      }
    });
  });