简体   繁体   中英

How to parse XML string with Prototype?

I have a string <ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul> and on client side I have to convert it to JSON. Something like {data:['Foo','Bar'],params:['100;50','200;150']}

I found a pretty good way to achieve it in here so my code should be something like that

var $input = $(input);
var data = "data:[";
var params = "params:[";

var first = true;
$input.find("li").each(function() {
    if (!first) {
        data += ",";
        params += ",";
    } else {
        first = false;
    }
    data += "'" + $(this).text() + "'";
    var e = $(this).attr("e");
    var n = $(this).attr("n");
    params += "'" + e + ';' + n + "'";
});

return "{data + "]," + params + "]}";

But the problem is that I can't use jquery. How can I do the same thing with prototype?

You want to use a DOM parser:

https://developer.mozilla.org/en/DOMParser

Something like this...

var xmlStr = '<ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul>';

var parser = new DOMParser();
var doc = parser.parseFromString(xmlStr, "application/xml");

var rootElement = doc.documentElement;
var children = rootElement.childNodes;

var jsonObj = {
    data: [],
    params: []
};

for (var i = 0; i < children.length; i++) {
    // I realize this is not how your implementation is, but this should give
    // you an idea of how to work on the DOM element
    jsonObj.data.push( children[i].getAttribute('e') );
    jsonObj.params.push( children[i].getAttribute('n') );
}

return jsonObj.toJSON();

Also, don't manually build your JSON string. Populate an object, then JSON-encode it.

Edit: Note that you need to test for DOMParser before you can use it. Check here for how you can do that. Sorry for the W3Schools link.

Why you are building an array object with string? Why not

var data = new Array();
var params = new Array();

$$("li").each(function() {
    data.push ($(this).text());
    params.psuh($(this).attr("e") + ";" + $(this).attr("n"));
});


return {data:data.toString(), params:params.toString()};

or

return {data:data, params:params};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM