2015-04-16 52 views
-1
<XML> 
    <EVENT> 
    <SHOPS> 
     <SHOP shopid="0001" name="London" city="LONDON"/> 
    </SHOPS> 
    <HISTORY> 
     <WIN shopid="0001" amount="2000" time="2015-03-28 19:09:23"/> 
    </HISTORY> 
    </EVENT> 
</XML> 

你會如何在xml文件中編寫這個Nokogiri查詢?Nokogiri XML查詢

  1. 迭代通過XML文件,並找到屬性量> 900
  2. 得到這個節點的屬性shopid
  3. 檢索名稱和數量> 900
+2

歡迎堆棧溢出。不是我們爲您編寫代碼,您應該向我們展示您嘗試過的內容,並嘗試幫助解決問題。 –

回答

2
的shopid的城市節點

這裏的「長路」爲例,使用大量的紅寶石和文檔走動:

require 'nokogiri' 
doc = Nokogiri.XML(File.read('my.xml')) 

wins = doc.search('WIN') 
wins_with_amount = wins.select{ |win| win['amount'] } 
first_big = wins_with_amount.find{ |win| win['amount'].to_i > 900 } 
shop_id = first_big['shopid'] 
shop  = doc.search('SHOP').find{ |shop| shop['shopid']==shop_id } 
puts shop['name'], shop['city'] 

的快速的方式,只使用XPath的:

require 'nokogiri' 
doc = Nokogiri.XML(File.read('my.xml')) 

shop = doc.at('//SHOP[@shopid=//WIN[@amount>900]/@shopid]') 
puts shop['name'], shop['city'] 

解釋說,XPath查詢:

  • //SHOP - 找到所有SHOP元素
    • [@shopid=...] ...其shopid屬性這一標準
    • //WIN匹配 - 查找全部WIN元素
      • [@amount>900] ...有一個amount屬性,它的值大於900
        • /@shopid ...找到這些WIN元素shopid屬性。
+0

謝謝!它完美的作品! – Snake