Convert XML to JSON (and back) using Javascript

后端 未结 12 1354
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:24

    You can also use txml. It can parse into a DOM made of simple objects and stringify. In the result, the content will be trimmed. So formating of the original with whitespaces will be lost. But this could be used very good to minify HTML.

    const xml = require('txml');
    const data = `
    <tag>tag content</tag>
    <tag2>another content</tag2>
    <tag3>
      <insideTag>inside content</insideTag>
      <emptyTag />
    </tag3>`;
    
    const dom = xml(data); // the dom can be JSON.stringified
    
    xml.stringify(dom); // this will return the dom into an xml-string
    

    Disclaimer: I am the author of txml, the fastest xml parser in javascript.

    0 讨论(0)
  • 2020-11-22 03:25

    https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):

    This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.

    API functions

    • new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
    • X2JS.xml2json - Convert XML specified as DOM Object to JSON
    • X2JS.json2xml - Convert JSON to XML DOM Object
    • X2JS.xml_str2json - Convert XML specified as string to JSON
    • X2JS.json2xml_str - Convert JSON to XML string

    Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/

    var x2js = new X2JS();
    function convertXml2JSon() {
        $("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
    }
    
    function convertJSon2XML() {
        $("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
    }
    
    convertXml2JSon();
    convertJSon2XML();
    $("#convertToJsonBtn").click(convertXml2JSon);
    $("#convertToXmlBtn").click(convertJSon2XML);
    
    0 讨论(0)
  • 2020-11-22 03:27

    I would personally recommend this tool. It is an XML to JSON converter.

    It is very lightweight and is in pure JavaScript. It needs no dependencies. You can simply add the functions to your code and use it as you wish.

    It also takes the XML attributes into considerations.

    var xml = ‘<person id=”1234” age=”30”><name>John Doe</name></person>’;
    var json = xml2json(xml); 
    
    console.log(json); 
    // prints ‘{“person”: {“id”: “1234”, “age”: “30”, “name”: “John Doe”}}’
    

    Here's an online demo!

    0 讨论(0)
  • 2020-11-22 03:29

    These answers helped me a lot to make this function:

    function xml2json(xml) {
      try {
        var obj = {};
        if (xml.children.length > 0) {
          for (var i = 0; i < xml.children.length; i++) {
            var item = xml.children.item(i);
            var nodeName = item.nodeName;
    
            if (typeof (obj[nodeName]) == "undefined") {
              obj[nodeName] = xml2json(item);
            } else {
              if (typeof (obj[nodeName].push) == "undefined") {
                var old = obj[nodeName];
    
                obj[nodeName] = [];
                obj[nodeName].push(old);
              }
              obj[nodeName].push(xml2json(item));
            }
          }
        } else {
          obj = xml.textContent;
        }
        return obj;
      } catch (e) {
          console.log(e.message);
      }
    }
    

    As long as you pass in a jquery dom/xml object: for me it was:

    Jquery(this).find('content').eq(0)[0]
    

    where content was the field I was storing my xml in.

    0 讨论(0)
  • 2020-11-22 03:29

    Disclaimer: I've written fast-xml-parser

    Fast XML Parser can help to convert XML to JSON and vice versa. Here is the example;

    var options = {
        attributeNamePrefix : "@_",
        attrNodeName: "attr", //default is 'false'
        textNodeName : "#text",
        ignoreAttributes : true,
        ignoreNameSpace : false,
        allowBooleanAttributes : false,
        parseNodeValue : true,
        parseAttributeValue : false,
        trimValues: true,
        decodeHTMLchar: false,
        cdataTagName: "__cdata", //default is 'false'
        cdataPositionChar: "\\c",
    };
    if(parser.validate(xmlData)=== true){//optional
        var jsonObj = parser.parse(xmlData,options);
    }
    

    If you want to parse JSON or JS object into XML then

    //default options need not to set
    var defaultOptions = {
        attributeNamePrefix : "@_",
        attrNodeName: "@", //default is false
        textNodeName : "#text",
        ignoreAttributes : true,
        encodeHTMLchar: false,
        cdataTagName: "__cdata", //default is false
        cdataPositionChar: "\\c",
        format: false, 
        indentBy: "  ",
        supressEmptyNode: false
    };
    var parser = new parser.j2xParser(defaultOptions);
    var xml = parser.parse(json_or_js_obj);
    
    0 讨论(0)
  • 2020-11-22 03:29

    The best way to do it using server side as client side doesn't work well in all scenarios. I was trying to build online json to xml and xml to json converter using javascript and I felt almost impossible as it was not working in all scenarios. Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC. Here is the online converter http://techfunda.com/Tools/XmlToJson

    0 讨论(0)
提交回复
热议问题