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.

swati
  • 129
  • 1
  • 18
  • Would you consider using library that would do parsing for you? – Matas Vaitkevicius Jun 13 '14 at 10:59
  • check this http://www.w3schools.com/xml/xml_parser.asp – Arsen Mkrtchyan Jun 13 '14 at 11:00
  • See related question http://stackoverflow.com/questions/17604071/parse-xml-using-javascript. – Mihai8 Jun 13 '14 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. – swati Jun 13 '14 at 11:09

2 Answers2

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
});
Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41
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.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265