将JavaScript XML DOM对象转换为具有特定结构的Object

时间:2018-06-13 14:21:34

标签: javascript xml xml-parsing xmldom

我有一个大的XML DOM对象,它通过jQuery的$.parseXML函数解析,返回一个JavaScript DOM对象。使用此XML,我想创建一个具有以下结构的普通JavaScript对象:

{
    name: 'my_tree',
    children: [
        { name: 'hello' },
        { name: 'wat' },
        {
            name: 'child_folder',
            children: [
                {
                    name: 'child_folder',
                    children: [
                        { name: 'hello' },
                        { name: 'wat' }
                    ]
                },
                { name: 'hello' },
                { name: 'wat' },
                {
                    name: 'child_folder',
                    children: [
                        { name: 'hello' },
                        { name: 'wat' }
                    ]
                }
            ]
        }
    ]
}

原始XML看起来像这样:

<my_tree>
    <hello></hello>
    <wat></wat>
    <child_folder>
        <child_folder>
            <hello></hello>
            <wat></wat>
        </child_folder>
        <hello></hello>
        <wat></wat>
        <child_folder>
            <hello></hello>
            <wat></wat>
        </child_folder>
    </child_folder>
</my_tree>

我尝试过类似下面的代码,但无济于事:

function xmlDomToObject(domObject) {
    var result = {children: []};
    for (var i = 0; i < domObject.length; i++) {
        if (domObject[i].nodeName == "#text") {
            continue;
        }

        result['name'] = domObject[i].nodeName;
        result['children'].push(xmlDomToObject(domObject[i].childNodes));
    }

    return result;
}

var xmlObject = xmlDomToObject(xmlDomObject.childNodes);

1 个答案:

答案 0 :(得分:1)

一种可能的方法如下。使用children(而不是childNodes)属性允许绕过文本节点并仅检查元素:

function parseXml(node) {
  const el = {
    name: node.nodeName
  };

  const children = Array.prototype.map.call(node.children, parseXml);
  // ES6: const children = [...node.children].map(parseXml);
  if (children.length) {
    el.children = children;
  }

  return el;
}

您可以按原样使用它,只记得传递documentElement结果的$.parseXML属性 - 而不是结果本身。

const xmlStr = `<my_tree>
    <hello></hello>
    <wat></wat>
    <child_folder>
        <child_folder>
            <hello></hello>
            <wat></wat>
        </child_folder>
        <hello></hello>
        <wat></wat>
        <child_folder>
            <hello></hello>
            <wat></wat>
        </child_folder>
    </child_folder>
</my_tree>`;

const xml = $.parseXML(xmlStr);
const parsed = parseXml(xml.documentElement);

console.log(parsed);

function parseXml(node) {
  const el = {
    name: node.nodeName
  };

  // const children = [...node.children].map(parseXml);
  const children = Array.prototype.map.call(node.children, parseXml);
  if (children.length) {
    el.children = children;
  }
 
  return el;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

相关问题