Convert xml-like format to json with javascript

Asked

Viewed 714 times

0

I am using the following code to read a file similar to an XML, but I need this file to be converted to a JSON, will anyone be able to give me this help ?
Follow the code of my index.html

<html>
<head>
    <script>
        var openFile = function(event) {
            var input = event.target;

            var reader = new FileReader();
            reader.onload = function() {
                var text = reader.result;
                var node = document.getElementById('output');
                node.innerText = text;
                console.log(reader.result.substring(0, 200));

                var xml, parser, xmlDoc;

                parser = new DOMParser();
                xmlDoc = parser.parseFromString(text, "text/xml");
                xmlDoc.getElementsByTagName("children")[0].childNodes.forEach(function(value) {
                    console.log(value.id);
                });


            };

            reader.readAsText(input.files[0]);
        };
    </script>
</head>
<body>
    <input type='file' accept='text/plain' onchange='openFile(event)'><br>
    <div id='output'>
        ...
    </div>
</body>
</html>

The file is written as follows in a file called Child.txt:

<item  name='MenuPrincipal' label='Menu Principal' >
    <children>
        <child id='child1' />
        <child id='child2'/>
        <child id='child3'/>
        <child id='child4'/>        
    </children>
</item>

I need to convert this file so that I get a Json.
Does anyone have any idea how I can do this magic ? kk Thank you.

  • 1

    For me this is yes XML, I do not see anything that says otherwise, so much is an XML that you even used DOMParser.

  • Right, his look appears to be an xml but is a language of its own, based on xml, but I can not convert this file to json direct, well at least I could not, if you have any suggestions I am open to try.

  • And what result do you want? {"item":[{"children": ["child1", "child2", "child3", "child4"]}]}?

  • exact i would like to achieve the return of Child’s id’s.

  • @Tonymontana if you have any suggestions thank you.

  • 2

    XML is a default language in the name of tags, you can create your XML with any tag you want to invent, create a proper tag or attribute for an element does not make it a new language.

  • @Guilhermenascimento I understood, but I will go into more detail: the actual extension of this file is ITD, and not XML so I need to read it as txt because although it is identical to an xml the structure is different and has no converter from itd to json hehe.

  • 3

    Extension being . xml, . itd, . foienaovoltou do not interfere with the content, this is just to facilitate Desktop programs to identify the document type without having to read, you can invent your own extension and yet it will be xml. It has many files that have own extensions like . manifest and web.conf (IIS) which are actually standardized XML files for a specific use, so what you have is a standardized XML file for this ITD. As I have already said XML is a customizable document, it does not mean that pq is customized that ceases to be XML.

  • @Guilhermenascimento po valeu cara, honestly did not know this rsrs I’m still new in programming but it was worth the explanation, I will edit the topic.

Show 4 more comments

1 answer

-1

I was able to find a complete solution to my problem.

Follow the code of index.html:

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Example external File with XML to JSON</title>
    <script type="text/javascript" src="xml2json.js"></script>
    <style type="text/css">
        h4 {
            position: relative;
            margin: 2px auto;
            text-align: left;
        }
        
        #jsnstr {
            margin: .35em .4em 1em 2em;
            max-height: 500px;
            background: #ffc;
            border: 1px solid #dadada;
            padding: .4em .5em;
            color: #333;
            font-weight: 800;
            overflow: auto;
        }
    </style>
</head>
<body>
    <h4>Result JSON</h4>
    <pre id="jsnstr"></pre>


    <script type="text/javascript" src="xml2json.js"></script>
    <script type="text/javascript">
        // <![CDATA[
        // gets the JSON string from a file with XML content ("test.xml")
        var jsonstr = xml2json.fromFile('test.xml', 'string');

        // adds the JSON string in HTML element with id="jsnstr"
        document.getElementById('jsnstr').innerHTML = jsonstr;
        // ]]>
    </script>
</body>
</html>

Follow the code of the xml2json.js file:

// Converts XML to JSON
// from: http://coursesweb.net/javascript/convert-xml-json-javascript_s2
function XMLtoJSON() {
    var me = this; // stores the object instantce

    // gets the content of an xml file and returns it in 
    me.fromFile = function(xml, rstr) {
        // Cretes a instantce of XMLHttpRequest object
        var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        // sets and sends the request for calling "xml"
        xhttp.open("GET", xml, false);
        xhttp.send(null);

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xhttp.responseXML));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // returns XML DOM from string with xml content
    me.fromStr = function(xml, rstr) {
        // for non IE browsers
        if (window.DOMParser) {
            var getxml = new DOMParser();
            var xmlDoc = getxml.parseFromString(xml, "text/xml");
        } else {
            // for Internet Explorer
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
        }

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xmlDoc));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // receives XML DOM object, returns converted JSON object
    var setJsonObj = function(xml) {
        var js_obj = {};
        if (xml.nodeType == 1) {
            if (xml.attributes.length > 0) {
                js_obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    js_obj["@attributes"][attribute.nodeName] = attribute.value;
                }
            }
        } else if (xml.nodeType == 3) {
            js_obj = xml.nodeValue;
        }
        if (xml.hasChildNodes()) {
            for (var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(js_obj[nodeName]) == "undefined") {
                    js_obj[nodeName] = setJsonObj(item);
                } else {
                    if (typeof(js_obj[nodeName].push) == "undefined") {
                        var old = js_obj[nodeName];
                        js_obj[nodeName] = [];
                        js_obj[nodeName].push(old);
                    }
                    js_obj[nodeName].push(setJsonObj(item));
                }
            }
        }
        return js_obj;
    }

    // converts JSON object to string (human readablle).
    // Removes '\t\r\n', rows with multiples '""', multiple empty rows, '  "",', and "  ",; replace empty [] with ""
    var jsontoStr = function(js_obj) {
        var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\\t|\\r|\\n)/g, '').replace(/"",[\n\t\r\s]+""[,]*/g, '').replace(/(\n[\t\s\r]*\n)/g, '').replace(/[\s\t]{2,}""[,]{0,1}/g, '').replace(/"[\s\t]{1,}"[,]{0,1}/g, '').replace(/\[[\t\s]*\]/g, '""');
        return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';
    }
};

// creates object instantce of XMLtoJSON
var xml2json = new XMLtoJSON();

In order to be shown a result in fact just create a file called "test.xml" and insert the xml information inside.

I thank everyone who clarified my doubts and especially @Guilhermenascimento, because thanks to their clarifications I was able to find a more appropriate solution to my need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.