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

I have an XML file:

<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 contains 500 elements boxthat I need to parse for JavaScript objects. I use this code, which works great, but I'm a beginner and maybe I'm missing something and would like to get suggestions if there is a better / faster way to do this:

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.

+5
source share
3 answers

Use JSON if at all possible. This way the browser will do the parsing for you, and you won’t have to do the post processing.

JSON from the server

{"content":
  {"box": [
    {"var1": "A1",
     "var2": "B1",
     "var3": "C1",
     "var4": "D1"},
    {"var1": "A2",
     "var2": "B2",
     "var3": "C2",
     "var4": "D2"},
    {"var1": "A3",
     "var2": "B3",
     "var3": "C3",
     "var4": "D3"}]}}

Client javascript

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

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

        $.ajax({
            type: "GET",
            url: file,
            dataType: "json",
            success: function(result) {
              that.box = $.map(result.content.box, function(box, i) {
                return new Box(i, box);
              });
            }
        });
    },
    //...
};
+2

XML, . JSON , .. ..

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
    });

};

XML2JSON, : http://www.thomasfrank.se/xml_to_json.html

+3

All Articles