Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to parse the below xml data by traversing through each node.

<example>
<name>BlueWhale</name>
<addr>101 Yesler Way, Suite 402</addr>
<city>Seattle</city>
<state>Washington</state>
</example>

Now I want to access each node without doing getElementsByTagName and print each NodeName & NodeValue in javascript, with the help of things like, rootElement,firstchild,nextSibling which i am not sure of.

I am trying the following manner

var txt = " <example>  <name>BlueWhale</name> <addr>101 Yesler Way, Suite 402</addr>  <city>Seattle</city>  <state>Washington</state>  </example> "
var domParser = new DOMParser();
xml = domParser.parseFromString(txt, "text/xml");
var el =xml.documentElement.nodeName;
console.log(el);

and print each var. Could anyone please help.

share|improve this question
    
what have you tried? what is your issue/question? –  ArsenMkrt Jun 13 at 10:59
    
Would you consider using library that would do parsing for you? –  LIUFA Jun 13 at 10:59
    
check this w3schools.com/xml/xml_parser.asp –  ArsenMkrt Jun 13 at 11:00
    
    
Thank you for the responses, however 1) I don prefer using jQuery 2) I do not prefer doing it by getElementsByTagName, as while implementing it, xml data received is dynamic hence i wish to access each of it by position and not by tag name. –  swati Jun 13 at 11:09
add comment

2 Answers 2

You should consider using library that does that for you rather than doing it by hand. One of commonly used one's you can find here.

share|improve this answer
add comment

if you xml is stored inside a string variable you can use jQuery.

var xml = "<example>...";

$(xml).children().each(function() {
    var tagName = this.tagName;
    var text = this.innerHtml
});
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.