如何使用Javascript解析嵌套的XML文件?

时间:2011-07-21 15:24:29

标签: javascript xml

<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>

我有以前的XML文件,我想用Javascript解析它,如何访问特定类型的所有子类型?

我用过

var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Type"); 

解析Types,但是我如何解析每种类型的Subtypes?

2 个答案:

答案 0 :(得分:1)

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

}

那应该让你到那里......尽管

,你想用这些子类做什么

答案 1 :(得分:0)

您也可以使用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