i’m trying to write a function that will loop through XML/DOM and store all the node names, values (if any) and attributes (if any) into a javascript object.
here’s my very basic XML file…
<?xml version="1.0" encoding="iso-8859-1"?>
<data>
<people>
<person firstname="Bob" lastname="Jones">
<email>bobjones@aol.com</email>
<mobile>865-555-5555</mobile>
</person>
<person firstname="Larry" lastname="Smith">
<email>larrysmith@yahoo.com</email>
<mobile>865-444-4444</mobile>
</person>
<person firstname="Wanda" lastname="Williams">
<email>wandawilliams@hotmail.com</email>
<mobile>865-333-333</mobile>
</person>
</people>
<computers>
<computer brand="Apple">
<model>MacBook</model>
<year>2007</year>
</computer>
<computer brand="Sony">
<model>VAIO</model>
<year>2007</year>
</computer>
</computers>
</data>
i’m passing along the XML document via AJAX (var doc = req.responseXML.documentElement).
i can step through the nodes, but not dynamically, which is what i want to do since i’m going to be manipulating multiple XML documents.
for example, this will output the first couple of levels. real basic, but not dynamic. if i had an XML file with 20 levels i’d have to make one long for() loop.
var result = doc.nodeName;
for (var i = 0; i < doc.childNodes.length; i++) {
if (doc.childNodes[i].nodeType == 1) {
result += "\
\ " + doc.childNodes[i].nodeName;
for (var j = 0; j < doc.childNodes[i].childNodes.length; j++) {
if (doc.childNodes[i].childNodes[j].nodeType == 1) {
result += "\
\ \ " + doc.childNodes[i].childNodes[j].nodeName + " (" + doc.childNodes[i].childNodes[j].childNodes.length + ")";
}
}
}
}
alert(result);
how can i dynamically step through the document object?