1
votes

Why doesn't the following 'normal' XPath work using 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"] is a valid XPath by the standards and works in several other utilities but it seems lxml has a very odd way of addressing namespaces:

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

Is it possible to address the namespace without defining it as a dict next to the xpath?

1
What do you mean it doesn't work? Do you get an error? - John Gordon
@JohnGordon updated it -- it 'works' I'm just wondering if it can be done without using that namespace map. - samuelbrody1249

1 Answers

1
votes

It's not necessarily more elegant than using namespaces, but this gets you to the same place:

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

Output:

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