gpt4 book ai didi

ruby - 如何使 xpath 表达式只读取文档的一部分 (Ruby/Nokogiri/xpath)

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:05 26 4
gpt4 key购买 nike

我使用 Ruby 1.9.3p385、Nokogiri 和 xpath v.1。

在 Stackoverflow 上很棒的人的帮助下,我想出了这个 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

如您所见,这完全符合我的要求,除了一件事:它读取产品而不是产品。

如何将我的搜索仅限于产品?回答时,请注意示例已简化。我更希望该解决方案“删除”产品知识(如果可能),因为这样它可能适用于所有情况。

最佳答案

代替:

//*[not(*)] 

使用:

(//product)[1]//*[not(*)] 

这仅选择 XML 文档中第一个 product 元素下的“叶节点”。

对文档中的所有 product 元素重复此操作。您可以通过以下方式获得他们的数量:

count(//product)

关于ruby - 如何使 xpath 表达式只读取文档的一部分 (Ruby/Nokogiri/xpath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729485/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com