0

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.

1
  • Would a function that converts XML to JSON help you solve this problem? Commented Mar 27, 2012 at 17:27

1 Answer 1

1

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>

var xml='<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></newsmodule>';


  xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find( "year[name='2012']" );

$("body").append($($title).find("date").text());

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.