Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering Namespace in Python XPath query

This is the XML document that I have:

<products xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Product Id="1">
      <Product Id="1_1">
        <Attribute Name="Whatever"></Attribute>
      </Product>
      <Attributes xmlns="http://some/path/to/entity/def">
        <Attribute Name="Identifier">NumberOne</Attribute>
      </Attributes>
  </Product>
  <Product Id="2">
    <Attributes xmlns="http://some/path/to/entity/def">
      <Attribute Name="Identifier">NumberTwo</Attribute>
    </Attributes>
  </Product>
</products>

I'm trying to use XPath for getting a Product by its child Attributes.Attribute[Name=Identifier] value (e.g. "NumberOne"). So in that case my expected result would be:

<Product Id="1">
      <Product Id="1_1">
        <Attribute Name="Whatever"></Attribute>
      </Product>
      <Attributes xmlns="http://some/path/to/entity/def">
        <Attribute Name="Identifier">NumberOne</Attribute>
      </Attributes>
</Product>

Based on this explanation, I tried to implement the query in Python by using the lxml lib:

found_products = xml_tree_from_string.xpath('//products//Product[c:Attributes[Attribute[@Name="Identifier" and text()="NumberOne"]]]', namespaces={"c": "http://some/path/to/entity/def"})

Unfortunately, this never returns a result due to the Attributes namespace definition.

What am I missing?

like image 224
user2549803 Avatar asked Apr 16 '26 03:04

user2549803


1 Answers

What am I missing?

You're missing that Attribute is also in the same namespace as Attributes because default namespace declarations are inherited by descendent XML elements.

So, just add a c: to Attribute in your XPath, and it should work as you observed in your comment to Jack's answer.

like image 86
kjhughes Avatar answered Apr 18 '26 18:04

kjhughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!