0

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.

4
  • Would you consider using library that would do parsing for you? Commented Jun 13, 2014 at 10:59
  • check this w3schools.com/xml/xml_parser.asp Commented Jun 13, 2014 at 11:00
  • See related question stackoverflow.com/questions/17604071/parse-xml-using-javascript. Commented Jun 13, 2014 at 11:01
  • 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. Commented Jun 13, 2014 at 11:09

2 Answers 2

1

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
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.