2012-05-21 62 views
0

我有這樣的XML文件,我想找到這些查詢:XPath查詢 - 布爾條件

  1. 所有包含圖片
  2. 所有與多張圖片的書籍書籍
  3. 所有誰與 「拉里·尼文」 寫了一本書,作者

這裏是XML:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE inventory SYSTEM "books.dtd"> 
<inventory> 
    <book num="b1"> 
     <title>Snow Crash</title> 
     <author>Neal Stephenson</author> 
     <publisher>Spectra</publisher> 
     <price>14.95</price> 
     <chapter> 
      <title>Snow Crash - Chapter A</title> 
      <paragraph> 
       This is the <emph>first</emph> paragraph. 
       <image file="firstParagraphImage.gif"/> 
       afetr image... 
      </paragraph> 
      <paragraph> 
       This is the <emph>second</emph> paragraph. 
       <image file="secondParagraphImage.gif"/> 
       afetr image... 
      </paragraph> 
     </chapter> 
     <chapter> 
      <title>Snow Crash - Chapter B</title> 
      <section> 
       <title>Chapter B - section 1</title> 
       <paragraph> 
        This is the <emph>first</emph> paragraph of section 1 in chapter B. 
        <image file="Chapter_B_firstParagraphImage.gif"/> 
        afetr image... 
       </paragraph> 
       <paragraph> 
        This is the <emph>second</emph> paragraph of section 1 in chapter B. 
        <image file="Chapter_B_secondParagraphImage.gif"/> 
        afetr image... 
       </paragraph> 
      </section> 
     </chapter> 
     <chapter> 
      <title>Chapter C</title> 
      <paragraph> 
       This chapter has no images and only one paragraph 
      </paragraph> 
     </chapter> 
    </book> 
    <book num="b2"> 
     <title>Burning Tower</title> 
     <author>Larry Niven</author> 
     <author>Jerry Pournelle</author> 
     <publisher>Pocket</publisher> 
     <price>5.99</price> 
     <chapter> 
      <title>Burning Tower - Chapter A</title> 
     </chapter> 
     <chapter> 
      <title>Burning Tower - Chapter B</title> 
      <paragraph> 
       This is the <emph>second</emph> paragraph of chapter B in the 2nd book. 
       <image file="Burning_Tower_Chapter_B_secondParagraphImage.gif"/> 
       afetr image... 
      </paragraph> 
     </chapter> 
    </book> 
    <book num="b3"> 
     <title>Zodiac</title> 
     <author>Neal Stephenson</author> 
     <publisher>Spectra</publisher> 
     <price>7.50</price> 
     <chapter> 
      <title>Zodiac - Chapter A</title> 
     </chapter> 
    </book> 
    <!-- more books... --> 
</inventory> 

這裏是我的答案:

1. /inventory/book[count(image)=1]/title 
2. /inventory/book[count(image)>=1/title 
3. /inventory/book[author=」Larry Niven」][count(author)>1]/author 

但是當我測試這些答案與Java的XPath代碼,它不工作。

哪裏出錯?感謝

回答

2

你的前兩個都涉及到image是在文檔中的問題 - 需要從目前的網絡搜索和搜索所有的兒童(而不僅僅是直接的小孩):

/inventory/book[count(.//image) = 1]/title 
/inventory/book[count(.//image) >= 1]/title 

你的最後一個有問題報價(需要使用單引號),並且還重複Larry Niven。這裏是修復:

/inventory/book[author='Larry Niven'][count(author) > 1]/author[. != 'Larry Niven'] 

注意您可以使用and代替:

/inventory/book[author='Larry Niven' and count(author) > 1]/author[. != 'Larry Niven']