Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the fastest way to parse my XML into JavaScript objects using jQuery?

I have an XML file like this:

<content>
    <box>
        <var1>A1</var1>
        <var2>B1</var2>
        <var3>C1</var3>
        <var4>D1</var4>
    </box>
    <box>
        <var1>A2</var1>
        <var2>B2</var2>
        <var3>C2</var3>
        <var4>D2</var4>
    </box>
    <box>
        <var1>A3</var1>
        <var2>B3</var2>
        <var3>C3</var3>
        <var4>D3</var4>
    </box>
</content>

It has 500 box elements which I need to parse into JavaScript objects. I am using this code which works fine but I am a newbie and maybe I am missing something and would like to get suggestions if there is a better/faster way to do it:

var app = {
    //...
    box: [],

    init: function (file) {
        var that = this;

        $.ajax({
            type: "GET",
            url: file,
            dataType: "xml",
            success: function (xml) {
                $("box", xml).each(function (i) {
                    var e = $(this);
                    that.box[i] = new Box(i, {
                        var1: e.children("var1").text(),
                        var2: e.children("var2").text(),
                        var3: e.children("var3").text(),
                        var4: e.children("var4").text()
                    });
                });
            }
        });
    },
    //...
};

Thanks in advance.

like image 559
VerizonW Avatar asked Jan 19 '11 02:01

VerizonW


1 Answers

I have an XML source I am forced to use.. I convert it to JSON on the client side and then load it.. much easier..

Tracker.loadCasesFromServer = function () {
$.ajax({
    type: 'GET',
    url: '/WAITING.CASES.XML',
    dataType: 'xml',
    success: function (data) {
            Tracker.cases = jQuery.parseJSON(xml2json(data, ""));
            Tracker.loadCasesToMap();
        },
        data: {},
        async: true
    });

};

Used the XML2JSON converter that can be found here: http://www.thomasfrank.se/xml_to_json.html

Duncan

like image 188
Duncan_m Avatar answered Sep 23 '22 21:09

Duncan_m