Search code examples
javascriptjsonprototypejs

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?


Solution

  • 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.