Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  104] [ 7]  / answers: 1 / hits: 9470  / 11 Years ago, wed, february 26, 2014, 12:00:00

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


More From » html

 Answers
20

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.


[#47354] Wednesday, February 26, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ethanc

Total Points: 57
Total Questions: 111
Total Answers: 111

Location: Vanuatu
Member since Fri, May 13, 2022
2 Years ago
;