简体   繁体   English

递归xml解析功能未按预期工作

[英]recursive xml-parsing function not working as intended

I'm trying to parse an XML document and use the data to build a (simpler) json object of this form: 我正在尝试解析XML文档并使用数据来构建这种形式的(简单)json对象:

{id: '1', name: 'content-types', children: [{id: '2', name: 'requirements': children: [... and so on ...]]}

My XML has nodes that look like the following (I've only included one -- they can be arbitrarily nested): 我的XML具有如下所示的节点(我仅包括其中一个-它们可以任意嵌套):

<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head/>
  <body class="taxonomies">
    <div class="taxonomy">
      <span class="id">3484069771</span>
      <span class="name">Content Types</span>
      <span class="locale">en</span>
      <div class="concepts">
        <div class="concept">
          <span class="id">3484058507</span>
          <span class="name">Promotional Publications</span>
          <div class="concepts">
            <div class="concept">
              <span class="id">3551765771</span>
              <span class="name">Datasheets</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

I use the following code to build a JSON tree from the XML: 我使用以下代码从XML构建JSON树:

buildConceptTree: function(xml){
    const doc = new dom().parseFromString(xml)
    var tree = []
    var selector = "//*[@class='taxonomies']"
    var count = 0  // this should keep track of the depth of the node being used
    function recurse(s, odd){
        var nodes
        console.log(count)
        console.log(s)
        var arr = []

        nodes = xpath.select(s, doc)
        nodes.forEach(node => {
            try {
                var children = node.childNodes
                var keys = Object.keys(children).filter(x => {return Number(x)})
                keys.forEach(key => {
                    var child = children[key]
                    console.log('child is: ')
                    console.log(child)
                    var obj = {}
                    var grandchildren = child.childNodes
                    var grandkeys = Object.keys(grandchildren).filter(x => {return Number(x)})

                    grandkeys.forEach(gk => {
                        var gc = grandchildren[gk]
                        try {
                            var nodevalue = gc['attributes'][0]['nodeValue']
                            switch(nodevalue){
                            case 'id':
                                obj['id'] = gc['textContent']
                            case 'name':
                                obj['name'] = gc['textContent']
                            case 'concepts':
                                count++
                                var rx = /taxonomy/
                                    if(!rx.test(s)){
                                        s = s+"/*[@class='taxonomy']"
                                    }
                                else{
                                    s = s
                                }
                                if (!odd){
                                    s += "/*[@class='concepts']"
                                }
                                else {
                                    s += "/*[@class='concept']"
                                }
                                odd = !odd
                                obj['children'] = recurse(s, odd)
                            }
                        }
                        catch(e){
                        }
                    })
                    arr.push(obj)
                })
            }
            catch(e){
            }

        })
        return arr


    }

    var tree = recurse(selector, false)
    return tree

},

As it stands, this function produces something like the JSON form I mentioned, but with many missing nodes. 就目前而言,此函数会产生类似于我提到的JSON形式的内容,但是缺少许多节点。

Also, it seems that my recursive function is not terminating in a simplest case as it recurs along deeper branches of the xml tree. 另外,似乎我的递归函数并没有在最简单的情况下终止,因为它沿着xml树的更深的分支递归。 I get the following logged in the console (for example), but there are no nodes that are 191 degrees deep: 我在控制台中记录了以下内容(例如),但是没有深度为191度的节点:

    191
     parser.js?d3c4:83 //*[@class='taxonomies']/*[@class='taxonomy']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']/*[@class='concept']/*[@class='concepts']
     parser.js?d3c4:92 child is:

Can anyone help me figure out how to change this function to make it get the data I want? 谁能帮助我找出如何更改此功能以使其获取所需的数据?

I might've missed some requirements, but the the issue seems less complicated once you stop looping over all elements and start querying the exact elements you expect: 我可能已经错过了一些要求,但是一旦停止循环浏览所有元素并开始查询所需的确切元素,该问题似乎就不那么复杂了:

 // Parse the xml string to a document const parser = new DOMParser(); const xmlDoc = parser.parseFromString( getXML(), "text/xml" ); // The main logic to go from an xml element to an object const parseTaxonomy = (taxonomy, id = 1) => ({ id, name: taxonomy.querySelector(".name") .innerText .toLowerCase() .replace(/\\s/g, "-"), children: Array.from( (taxonomy.querySelector(".concepts") || { children: [] }) .children ).map(t => parseTaxonomy(t, ++id)) // Note the ++ }); // Run on the first taxonomy // If the top level contains multiple elements, use .map console.log( parseTaxonomy( xmlDoc.querySelector(".taxonomy") ) ); // The data function getXML() { return `<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml"> <head/> <body class="taxonomies"> <div class="taxonomy"> <span class="id">3484069771</span> <span class="name">Content Types</span> <span class="locale">en</span> <div class="concepts"> <div class="concept"> <span class="id">3484058507</span> <span class="name">Promotional Publications</span> <div class="concepts"> <div class="concept"> <span class="id">3551765771</span> <span class="name">Datasheets</span> </div> </div> </div> </div> </div> </body> </html>`; }; 

Note: I changed the part in which you put the comment because the comment wasn't closed and I expected it to have another wrapper around the child taxonomies. 注意:我更改了您放置评论的部分,因为该评论尚未关闭,并且我希望它在子分类法周围有另一个包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM