How to parse nested XML file using Javascript?
<Types>
<Type id='1' name='sport'>
<SubTypes id='1' name='football' />
<SubTypes id='2' name='tennis' />
</Type>
<Type id='2' name='education'>
<SubTypes id='1' name='school' />
<SubTypes id='2' name='un开发者_运维技巧iversity' />
</Type>
</Types>
I have the previous XML file, and I want to parse it using Javascript, how can I access to all SubTypes for a specific Type ?
I used
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Type");
to parse the Types , but how can I parse the Subtypes for each type ?
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Type");
for (var i = 0; i < x.length; i++) {
var subTypes = new Array();
var y = x[i].getElementsByTagName("SubTypes")
for (var j = 0; j < y.length; j++){
subTypes.push(y[j])
// or you could just process them here
}
// process the subtypes in this type
}
That should get you there... idk what you want to do with these subtypes though
You could also use xpath:
var x = xmlhttp.responseXML;
var subtypes = x.evaluate( '//Types/Type/SubType', x.documentElement);
https://developer.mozilla.org/en-US/docs/Web/XPath/Introduction_to_using_XPath_in_JavaScript
精彩评论