Convert XML to JSON (and back) using Javascript

后端 未结 12 1375
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条回答
  •  故里飘歌
    2020-11-22 03:35

    I was using xmlToJson just to get a single value of the xml.
    I found doing the following is much easier (if the xml only occurs once..)

    let xml =
    '' +
      ' 762384324' +
      ' Hank ' +
      ' Stone' +
    '';
    
    let getXmlValue = function(str, key) {
      return str.substring(
        str.lastIndexOf('<' + key + '>') + ('<' + key + '>').length,
        str.lastIndexOf('')
      );
    }
    
    
    alert(getXmlValue(xml, 'firstname')); // gives back Hank

提交回复
热议问题