2009-10-25 49 views
3

我需要使用XPath節點的子節點,因爲我想「鑽」到一個節點的子節點。下面是我想要的代碼:紅寶石,libxml的獲得匹配的XPath

xml_ns = 'Document:http://www.google.com/books/' 

xml_document = XML::Document.file('./test_pages/test.xml') 
book_xpath = '//Document:View/Document:Books' 
book_title_xpath = '//Document:Title' 

xml_document.find(book_xpath, xml_ns).each() { | item | 
    puts item 
    item.find(book_title_xpath, xml_ns).each() { |item2| 
     puts '========================' 
     puts 'name: ' + item2.content().strip() 
    } 
} 

這裏是一個XML片段

<Document xmlns="http://www.google.com/books/"> 
    <View> 
     <Books> 
      <Title>pragmatic programming</Title> 
     </Books> 

     <Comics> 
      <Title>x-men</Title> 
     </Comics> 
    </View> 
</Document> 

先找工作找到並返回書節點。然而,第二個find(「//文件:標題」)返回所有標題節點的文件即使我只是在找到的節點搜索。

爲什麼會發生這種情況?我已經厭倦修改第二個XPath了,但是我已經厭倦了。有什麼建議?

回答

3

返回xml_document節點從來不從原始源打破。您始終可以前後移動,唯一的區別是「指針」位於當前找到的節點。

你需要做的是改變你的XPath,使得它不會做一個「完整的文檔搜索」:特殊//(這是「後代或自身」)從根開始並穿過所有節點。相反,請使用以下內容:

book_title_xpath = 'Document:Title' 

這將返回名爲「Title」的第一個孩子。如果您需要從圖書搜索節點的所有子節點,你可以做到以下幾點:

book_title_xpath = './/Document:Title' 

它增加了.和手段「開始在當前節點和搜索當前節點和所有後代」

+0

THX,以爲我已經試過了,但我想我沒有。 – 2009-10-26 13:13:55

0

嘗試

book_title_xpath = 'Title'