Convert XML to JSON (and back) using Javascript

后端 未结 12 1376
Happy的楠姐
Happy的楠姐 2020-11-22 03:18

How would you convert from XML to JSON and then back to XML?

The following tools work quite well, but aren\'t completely consistent:

  • xml2json
12条回答
  •  旧时难觅i
    2020-11-22 03:49

    In 6 simple ES6 lines:

    xml2json = xml => {                                                                                                                                                     
      var el = xml.nodeType === 9 ? xml.documentElement : xml                                                                                                               
      var h  = {name: el.nodeName}                                                                                                                                          
      h.content    = Array.from(el.childNodes || []).filter(e => e.nodeType === 3).map(e => e.textContent).join('').trim()                                                  
      h.attributes = Array.from(el.attributes || []).filter(a => a).reduce((h, a) => { h[a.name] = a.value; return h }, {})                                                 
      h.children   = Array.from(el.childNodes || []).filter(e => e.nodeType === 1).map(c => h[c.nodeName] = xml2json(c))                                                    
      return h                                                                                                                                                              
    }  
    

    Test with echo "xml2json_example()" | node -r xml2json.es6 with source at https://github.com/brauliobo/biochemical-db/blob/master/lib/xml2json.es6

提交回复
热议问题