我使用Ruby 1.9.3p385,Nokogiri和xpath v.1。如何僅通過文檔的一部分讀取xpath表達式(Ruby/Nokogiri/xpath)
與#2我想出了這個XPath表達式真棒人的幫助:
products = xml_file.xpath("(/root_tag/middle_tag/item_tag")
這個XML文件分割:
<root_tag>
<middle_tag>
<item_tag>
<headline_1>
<tag_1>Product title 1</tag_1>
</headline_1>
<headline_2>
<tag_2>Product attribute 1</tag_2>
</headline_2>
</item_tag>
<item_tag>
<headline_1>
<tag_1>Product title 2</tag_1>
</headline_1>
<headline_2>
<tag_2>Product attribute 2</tag_2>
</headline_2>
</item_tag>
</middle_tag>
</root_tag>
到2種產品。
我現在希望瀏覽每個產品並提取所有產品信息(通過提取其葉節點)。爲了這個目的,我使用此代碼:
products.each do |product|
puts product #=> <item_tag><headline_1><tag_1>Product title 1</tag_1></headline_1><headline_2><tag_2>Product attribute 1</tag_2></headline_2></item_tag>
product_data = product.xpath("//*[not(*)]")
puts product_data #=> <tag_1>Product title 1</tag_1><tag_2>Product attribute 1</tag_2><tag_1>Product title 2</tag_1><tag_2>Product attribute 2</tag_2>
end
正如你可以看到這不正是我想要的東西,exept一兩件事:它通過讀取產品的替代產品。
如何將搜索範圍限制爲產品?在回答時,請注意這個例子被簡化了。我寧願解決方案「擦除」產品的知識(如果可能的話),因爲它可能會在所有情況下都起作用。
'// * [not(*)]'中的''選擇器將xpath的範圍更改回文檔根元素('root_tag')。你需要使用本地選擇器來編寫它,比如'headline_1'或'headine_1/tag_1',而不是''''''。 –
好的,但你有建議可以處理這個表達式嗎?我在代碼中有這樣的:** paths = [「/ root_tag/middle_tag/item_tag/headline_1」,「/ root_tag/middle_tag/item_tag/headline_2」] **。也許我們可以提取**「headline_1」**和**「headline_2」**(這兩個部分不會出現),然後在本地搜索它們...... – JohnSmith1976
我是專業的刮板,所以如果你把一些$$,我可以爲你做,因爲你[請求](http:// stackoverflow。COM /問題/ 21752838 /如何做刮-A-網站與最socksify寶石代理)。如果你感興趣,請給我發一封電子郵件,正如我的個人資料中提到的 –