XML to CSV Conversion using Javascript

后端 未结 2 1109
野趣味
野趣味 2020-12-28 22:14

I am looking for some help trying to convert XML retrieved from Amazon Product API to convert it into CSV(Comma Separated Value) format.

I found a similar topic here

相关标签:
2条回答
  • 2020-12-28 22:51

    Try to use jQuery and it would be more simple - Ref Link : Simple XML to HTML Table

    0 讨论(0)
  • 2020-12-28 23:09

    After a long investigation i found out something that may help you.

    Starting from the point that reinventing the wheel is such a stupid and time consuming task, i was looking for what other good programmers have already built out there on the internet.

    Unfortunately I wasn't able to find out a direct converter form XML to CSV as the example you provide in PHP.

    In my working example the XML have to pass from JSON first like this:

    • xml2json => json2csv

    I took some pieces here and there and i will add the references of where i actually took all the code snippet i use for build the demo at the end of this answer. In this way you will be able to get a nice and clean documentation that will help you to improve this tool.

    Here a simple demo:

    function xmlTocsv() {
    
        var data = $("#xmlArea").val();
    
        var xml = "";
    
        if (data !== null && data.trim().length !== 0) {
    
            try {
                xml = $.parseXML(data);
            } catch (e) {
                throw e;
            }
    
            var x2js = new X2JS();
    
            data = x2js.xml2json(xml);
            jsonTocsvbyjson(data);
            
        }
    }
    
    function jsonTocsvbyjson(data, returnFlag) {
    
        arr = [];
        flag = true;
    
        var header = "";
        var content = "";
        var headFlag = true;
    
        try {
    
            var type1 = typeof data;
    
            if (type1 != "object") {
                data = processJSON($.parseJSON(data));
            } else {
                data = processJSON(data);
            }
    
        } catch (e) {
            if (returnFlag === undefined || !returnFlag) {
                console.error("Error in Convert to CSV");
            } else {
                console.error("Error in Convert :" + e);
            }
            return false;
        }
    
        $.each(data, function(k, value) {
            if (k % 2 === 0) {
                if (headFlag) {
                    if (value != "end") {
                        header += value + ",";
                    } else {
                        // remove last colon from string
                        header = header.substring(0, header.length - 1);
                        headFlag = false;
                    }
                }
            } else {
                if (value != "end") {
                    var temp = data[k - 1];
                    if (header.search(temp) != -1) {
                        content += value + ",";
                    }
                } else {
                    // remove last colon from string
                    content = content.substring(0, content.length - 1);
                    content += "\n";
                }
            }
    
        });
    
        if (returnFlag === undefined || !returnFlag) {
            $("#csvArea").val(header + "\n" + content);
        } else {
            return (header + "\n" + content);
        }
    }
    
    function processJSON(data) {
    
        $.each(data, function(k, data1) {
    
            var type1 = typeof data1;
    
            if (type1 == "object") {
    
                flag = false;
                processJSON(data1);
                arr.push("end");
                arr.push("end");
    
            } else {
                arr.push(k, data1);
            }
    
        });
        return arr;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
    <script type='text/javascript' src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>
    <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <h1>XML2CSV Demo</h1>
        <button id="convertToXmlBtn" onclick="xmlTocsv()">XML => CSV</button>
      
        <div>        
            <h4>XML:</h4>
            <textarea id="xmlArea" cols="55" rows="15"></textarea>
        </div>
        
        <div>
            <h4>CSV:</h4>
            <textarea id="csvArea" cols="55" rows="15"></textarea>
        </div>    
    </body>
    </html>

    References:

    • XML TO CSV Converter
    • x2js - XML to JSON and vice versa for JavaScript

    Utils:

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