1

I am displaying an XML document in an HTML file using JavaScript. So far everything is displaying well, but I want to display the second level of XML tags for <date>

My XML snippet looks like this:

<date>
    <dow>Monday</dow>
    <month>08</month>
    <day>10</day>
    <year>2011</year>
</date>

To display first level tags, I have been writing the following document write:

document.write(x[i].getElementsByTagName("date")[0].childNodes[0].nodeValue);

This however is not going to display <date>. I need to target the childNodes <dow>, <month>,<day>, and <year>. Can I tweak my current document.write to make this happen? I'm getting a bit stumped on how to direct this issue as I don't want to rewrite my entire code when first level elements are displaying just fine.

Any help would be greatly appreciated. Thank you in advance for your time.

3 Answers 3

2

You can use getElementsByTagName on any DOMElement:

var date = xml.getElementsByTagName("date")[0];
var dow = date.getElementsByTagName("dow")[0].childNodes[0].nodeValue;
console.log(dow);

Optimally, you should also be checking if the nodes exist before accessing them with foo[0].

http://jsfiddle.net/RT4Qr/

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

Comments

0

http://jsfiddle.net/efortis/vZAmS/

var xml = "<date><dow>Monday</dow><month>08</month><day>10</day><year>2011</year></date>",
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $dow = $xml.find( "dow" );

document.write( $dow.text() );

Here is the documentation http://api.jquery.com/jQuery.parseXML/

Comments

0

Thank you all for your help. I did end up getting the child tags to read. I actually was able to use the same code I used for the parent tags; however, placement of this document.write was messing with my head. I had to reformat the order of my code. I had placed my original code is an improper location on the page, was a brainless mistake. I learned a lot through my silly mistake here, and I won't do that again. lol. These are great options though too, so I appreciate your help. I will too look into these.

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.