I am working on a javascript project which involves parsing xml data. I have an xml file of the following structure:
<?xml version="1.0" encoding="utf-8"?>
<newsmodule>
<year name="2012">
<news>
<date>Jan 01</date>
<title>title 1</title>
<info>info 1</info>
</news>
<news>
<date>Jan 02</date>
<title>title 2</title>
<info>info 2</info>
</news>
</year>
<year name="2011">
<news>
<date>Jan 03</date>
<title>title 3</title>
<info>info 3</info>
</news>
<news>
<date>Jan 04</date>
<title>title 4</title>
<info>info 4</info>
</news>
</year>
I need to write every date for year 2012 in array. I used the following code:
$(xml).find("year").each(function () {
...
$(xml).find("news").each(function () {
dates.push($(this).find("date").text());
titles.push($(this).find("title").text());
infos.push($(this).find("info").text());
});
And for the obvious reason i’ve got data for all years in the same array.
Is there a way to get this to work? I may not change the xml file.
Don’t use jQuery’s DOM traversal methods to traverse through the XML that is very browser dependent use
parseXML, also if that is exactly the xml that you have posted that is malformed there is no ending</newsmodule>DEMO