简体   繁体   中英

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='university' />
   </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/Introduction_to_using_XPath_in_JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM