Convert XML to JSON (and back) using Javascript

后端 未结 12 1368
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: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);
    

提交回复
热议问题