【问题标题】:xmllint / Xpath extract parent node where child contains text from google shopping feedxmllint / Xpath 提取父节点,其中子节点包含来自谷歌购物提要的文本
【发布时间】:2021-02-06 07:35:51
【问题描述】:

我正在尝试提取所有包含 g:custom_label_0 且文本值为“2020-2021”的“项目”节点 到目前为止,我设法找到包含子 g:custom_label_0 的所有节点,但我没有设法按字段的文本值进行过滤。

这里是示例 XML:

   <item>
        <description>[...]</description>
        <g:availability>in stock</g:availability>
        <g:brand>Barts</g:brand>
        <g:condition>new</g:condition>
        <g:custom_label_0>2020-2021</g:custom_label_0>
        <g:id>108873/10-3</g:id>
        <g:image_link>[...]</g:image_link>
        <g:price>26.99 EUR</g:price>
        <g:sale_price>26.99 EUR</g:sale_price>
        <g:shipping>
            <g:country>NL</g:country>
            <g:price>4.50 EUR</g:price>
        </g:shipping>
        <g:shipping_weight>7.95</g:shipping_weight>
        <link>[....]</link>
    </item>
   ...

有节点包含除 2020-2021 之外的其他值,但我想提取包含此文本的所有完整项目节点。 这是我为提取具有可用字段的所有节点所做的。

xmllint --xpath '//item["g:custom_label_0"]' myfile.xml 

我尝试通过方括号等添加文本过滤器,但我觉得 custom_label_0 周围的引用可能会造成麻烦。在引号中添加更多过滤器被接受(没有错误),但我将无法在其中添加更多引号来过滤字符串。

工作正常,不报错:

xmllint --xpath '//item["g:custom_label_0[text()]"]' myfile.xml 

如果我现在想过滤文本,我需要再次使用引号。转义它们会破坏代码。当两种类型的引号都已使用时,如何进一步过滤文本“2020-2021”?

【问题讨论】:

标签: xpath xmllint google-shopping


【解决方案1】:

你是对的; g:custom_label_0 周围的引号引起了麻烦。这使它成为一个字符串,并且总是如此,因此它将返回所有 item 元素。

g: 是命名空间前缀。要将命名空间绑定到 xmllint 中的前缀,您必须在 shell 模式下使用它(参见 https://stackoverflow.com/a/8266075/317052 示例)。

另一种方法是测试元素名称以选择g:custom_label_0 元素,然后测试该元素的值以查看它是否为2020-2021

示例...

xmllint --xpath '//item[*[name()="g:custom_label_0"][.="2020-2021"]]' myfile.xml

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多