stackwitharray stackwitharray - 7 months ago 8
Javascript Question

How to parse XML in JavaScript

https://jsfiddle.net/recklesswish/6yw1tdwh/5/ The following link has the JSON and i have converted this particular JSON in XML. Now the issue is I am not getting that how to parse it using javascript.
Here is the code of xml, JSON resp.
XML

var carsData = "<cars>
"<Honda>"
"<model>Figo</model>"
"</Honda>"
"<Honda>"
"<model>City</model>"
"</Honda>"
"<Audi>"
"<model>A6</model>"
"</Audi>"
"<Audi>"
"<model>A8</model>"
"</Audi>"
"</cars>"


JSON

var carsData = '{"cars":{"Honda":[{"model":"Figo"},{"model":"City"}],"Audi":[{"model":"A6"},{"model":"A8"}]}}';

$('#newCollection').on('click', function() {
$(this).empty();
var data = JSON.parse(carsData);
$(this).append('New Collection<ul></ul>');

for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
$(this).find('ul').append('<li>' + make + ' - ' + model + '</li>')
}
}
});


With HTML

<ul>
<li id="newCollection">New Collection</li>
</ul>

Answer

First of all make your xml look like this in javascript -

var carsData = "<cars><Honda><model>Figo</model></Honda><Honda><model>City</model> </Honda><Audi><model>A6</model></Audi><Audi><model>A8</model></Audi></cars>"

And your JS code would look like this -

$('#newCollection').on('click', function() {
                        $(carsData).find("Honda").each(function() {
                            var model = $(this).find("model").text();
                            console.log("model: " + model );
                        });
                    });

newCollection is the id of your button. This will print model as below-

model: Figo
model: City

I would suggest you to go through basics first rather than trying to jump into coding directly. Clear basics will make you a good coder in long run :)

Comments