-1

I need some help on JavaScript, I have created a XML file I would to create a loop through all node elements with the help of JavaScript.The following is my XML file, so i need some help to print all the node names and the node values with the help of JavaScript, not JQUERY.


<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="children">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="web">
        <title lang="en">XQuery Kick Start</title>
        <author>James McGovern</author>
        <author>Per Bothner</author>
        <author>Kurt Cagle</author>
        <author>James Linn</author>
        <author>Vaidyanathan Nagarajan</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
    <book category="web" cover="paperback">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>

Thank You

user3350333
  • 69
  • 2
  • 8
  • possible duplicate of [Javascript: How to loop through ALL DOM elements on a page?](http://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page) – helderdarocha Feb 26 '14 at 22:16
  • `var all = document.getElementsByTagName("*");` see http://stackoverflow.com/questions/4256339/javascript-how-to-loop-through-all-dom-elements-on-a-page – helderdarocha Feb 26 '14 at 22:17
  • You can also do it recursively, getting all children, checking their DOM type, and either getting their name, value and attributes or recursing again if a node-set is found. – helderdarocha Feb 26 '14 at 22:19
  • can you provide me a little bit more details, and i am stuck with this for last 4 days.I need this to be solved asap. Thank you – user3350333 Feb 26 '14 at 22:26

1 Answers1

3

You can use browser built-in xml parser to do so. But it is more convenient to use JSON with Javascript.

var txt = "..."; // here is your xml as a string

if (window.DOMParser) {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(txt,"text/xml");
} else { // Internet Explorer
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.loadXML(txt); 
}

Then you can manipulate with xmlDoc as with DOM tree. For example lets alert all tag names and values:

var tags = xmlDoc.getElementsByTagName('*');
for (var i = 0; i < tags.length; i++) {
    alert(tags[i].nodeName + ' = ' + tags[i].firstChild.nodeValue);
}

Or probably XSLT can help you (Click on the "Try it Yourself" button to see how it works.). This is way to transform XML data to html page.

Yaroslav Admin
  • 13,880
  • 6
  • 63
  • 83