2011-11-09 20 views
1

javascriptでXMLに苦労していますが、特定の属性値を持つタグだけを選択するにはどうすればよいですか?タグ属性でXMLタグを取得する方法

w3 schoolsから次の例では、このxml file使用しています。

<?xml version="1.0" encoding="ISO-8859-1"?> 

<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"> 
    <title lang="en">Learning XML</title> 
    <author>Erik T. Ray</author> 
    <year>2003</year> 
    <price>39.95</price> 
</book> 

</bookstore> 

をしてから、次のスクリプトは、価格のタグからすべてのテキストを取得し、新しい行に印刷されます。

<html> 
<body> 
    <script type="text/javascript"> 
     function loadXMLDoc(dname){ 
      if (window.XMLHttpRequest){ 
       xhttp=new XMLHttpRequest(); 
      } 
      else{ 
       xhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } 

      xhttp.open("GET",dname,false); 
      xhttp.send(""); 
      return xhttp.responseXML; 
     } 
     //getting the xml into a var to parse  
     xml=loadXMLDoc("books.xml"); 


     //the path in question 
     path="/bookstore/book/price/text()" ////how can i change this to only select the prices of the books where the category="COOKING" ? 


     // code for IE 
     if (window.ActiveXObject){ 
      var nodes=xml.selectNodes(path); 

      for (i=0;i<nodes.length;i++) 
       { 
        document.write(nodes[i].nodeValue); 
        document.write("<br />"); 
       } 
     } 
     // code for Mozilla, Firefox, Opera, etc. 
     else if (document.implementation && document.implementation.createDocument){ 
      var nodes=xml.evaluate(path, xml, null, XPathResult.ANY_TYPE,null); 
      var result=nodes.iterateNext(); 

      while (result) 
       { 
        document.write(result.nodeValue + "<br />"); 
        result=nodes.iterateNext(); 
       } 
     } 
    </script> 
</body> 
</html> 

スクリプトは、親タグの本は '「COOKING」のカテゴリ属性を持っている価格タグのテキストをプリントアウトするようにパスを変更することは可能です(私は、スクリプト内にコメントを入れます現在のパスは私が変更する必要があると思っていますが、私はどのように見つけることができません)?

私は本当に立ち往生しており、それを手に入れる方法を見つけることができないようです。どんな助けが素晴らしいだろう:)

答えて

3

あなたのパスには、例えば//bookName/[@CATEGORY = COOKING]を置く必要があります。@は属性を調べる場所です。お役に立てれば。

関連する問題