LXML 命名空间前缀

LXML namespace prefix

为什么以下 'normal' XPath 使用 lxml 不起作用:

# Note: "Rows" is obviously not a real namespace, but for internal segmentation
xml_str = '''
<Data xmlns:R="Rows" xmlns:C="Columns" xmlns:V="Values">
    <R:ProductGroup value="Electronics">
    <R:Product value="Computer">
        <C:Year value="2018">
            <V:SumOfRevenue value="104"/>
            <V:SumOfUnits   value="3"/>
        </C:Year>
        <C:Year value="2019">
            <V:SumOfRevenue value="82"/>
            <V:SumOfUnits   value="9"/>
        </C:Year>
        <C:Year value="(all)">
            <V:SumOfRevenue value="186"/>
            <V:SumOfUnits   value="12"/>
            </C:Year>
        </R:Product>
    </R:ProductGroup>
</Data>
'''

from lxml import etree
node=etree.fromstring(xml_str)

//R:ProductGroup[@value="Electronics"] 是符合标准的有效 XPath,并且可以在其他几个实用程序中使用,但似乎 lxml 有一种非常奇怪的命名空间寻址方式:

node.xpath('//R:ProductGroup[@value="Electronics"]', namespaces={'R':'Rows'})
[<Element {Rows}ProductGroup at 0x7f05836bec08>]

是否可以在不将其定义为 xpath 旁边的字典的情况下对命名空间进行寻址?

它不一定比使用命名空间更优雅,但这会让你到达同一个地方:

node.xpath('//*[local-name()="ProductGroup"][@value="Electronics"]')

输出:

[<Element {Rows}ProductGroup at 0x1790b6fb240>]