XML to JavaScript Object

后端 未结 4 1714
情歌与酒
情歌与酒 2020-11-27 19:12

I am looking for a JavaScript library that parses an XML string and converts it to a JavaScript object. What are some good ones?

相关标签:
4条回答
  • 2020-11-27 19:28

    Going straight to the point (using node-xml2json):

    npm install xml2json
    

    Then, use it:

    const parser = require('xml2json');
    
    const obj = parser.toJson(xml, { object: true });
    

    Example:

    const parser = require('xml2json');
    
    const xml = '<root><person><name>Bob Dylan</name></person></root>';
    
    const obj = parser.toJson(xml, { object: true });
    const { person } = obj.root;
    person.name; // Bob Dylan
    

    You can also convert from JSON to XML, and much more.

    0 讨论(0)
  • 2020-11-27 19:30

    parses XML and returns a javascript object w/ a scheme that corresponds the xml. xml siblings w/ the same name are collapsed into arrays. nodes with names that can be found in the arrayTags parameter (array of tag name strings) always yeld arrays even in case of only one tag occurrence. arrayTags can be omitted. text nodes w/ only spaces are discarded. use console.log(parseXml(myxml)) to explore the output

    parseXml(xml, arrayTags)
    {
        var dom = null;
        if (window.DOMParser)
        {
            dom = (new DOMParser()).parseFromString(xml, "text/xml");
        }
        else if (window.ActiveXObject)
        {
            dom = new ActiveXObject('Microsoft.XMLDOM');
            dom.async = false;
            if (!dom.loadXML(xml))
            {
                throw dom.parseError.reason + " " + dom.parseError.srcText;
            }
        }
        else
        {
            throw "cannot parse xml string!";
        }
    
        function isArray(o)
        {
            return Object.prototype.toString.apply(o) === '[object Array]';
        }
    
        function parseNode(xmlNode, result)
        {
            if (xmlNode.nodeName == "#text") {
                var v = xmlNode.nodeValue;
                if (v.trim()) {
                   result['#text'] = v;
                }
                return;
            }
    
            var jsonNode = {};
            var existing = result[xmlNode.nodeName];
            if(existing)
            {
                if(!isArray(existing))
                {
                    result[xmlNode.nodeName] = [existing, jsonNode];
                }
                else
                {
                    result[xmlNode.nodeName].push(jsonNode);
                }
            }
            else
            {
                if(arrayTags && arrayTags.indexOf(xmlNode.nodeName) != -1)
                {
                    result[xmlNode.nodeName] = [jsonNode];
                }
                else
                {
                    result[xmlNode.nodeName] = jsonNode;
                }
            }
    
            if(xmlNode.attributes)
            {
                var length = xmlNode.attributes.length;
                for(var i = 0; i < length; i++)
                {
                    var attribute = xmlNode.attributes[i];
                    jsonNode[attribute.nodeName] = attribute.nodeValue;
                }
            }
    
            var length = xmlNode.childNodes.length;
            for(var i = 0; i < length; i++)
            {
                parseNode(xmlNode.childNodes[i], jsonNode);
            }
        }
    
        var result = {};
        for (let i = 0; i < dom.childNodes.length; i++)
        {
            parseNode(dom.childNodes[i], result);
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-27 19:38

    The xml2json javascript file from https://bitbucket.org/surenrao/xml2json is all you need to do this.

    Here's the download link for quick download: https://bitbucket.org/surenrao/xml2json/get/0e0989dfe48e.zip

    Once included in your project, here's some sample code to get you started:

    var xmlStr = "<root><person><name>Bob Dylan</name></person></root>";
    var jsObj = X2J.parseXml(xmlStr);
    var result = jsObj[0].root[0].person[0].name[0].jValue; //Bob Dylan
    
    0 讨论(0)
  • 2020-11-27 19:39

    Here's a nice xml2json and json2xml converter:

    • http://goessner.net/download/prj/jsonxml/
      • Related tutorial: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html

    Here's another one:

    • http://www.kawa.net/works/js/xml/objtree-e.html

    Depending on your needs, you might be able to use a standard parser (see http://www.w3schools.com/XML/tryit.asp?filename=tryxml_parsertest2) and xpath (http://www.w3schools.com/xpath/default.asp) - here's an example:

    • http://snippets.dzone.com/posts/show/5272

    and a few nice tutorials:

    • http://www.nczonline.net/blog/2009/03/17/xpath-in-javascript-part-1/
    • https://developer.mozilla.org/en/introduction_to_using_xpath_in_javascript
    0 讨论(0)
提交回复
热议问题