xmllint / Xpath 提取父节点,其中子节点包含来自 google 购物提要的文本

xmllint / Xpath extract parent node where child contains text from google shopping feed

我正在尝试提取所有包含 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”?

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

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

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

示例...

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