xmllint / Xpath提取父节点,其中子节点包含来自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周围的引号引起了麻烦。这使它成为字符串,并且始终为真,因此它将返回所有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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...