Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find element attribute using lxml

Tags:

python

xml

lxml

Suppose I have the the following xml:

<package xmlns="http://example/namespace">
    <rating system="au-oflc">PG</rating>
    ...
</package>

To get the text of an element in the above, I am doing the following:

from lxml import entree
f = open('/Users/David/Desktop/metadata.xml')
metadata_contents = f.read()
node = etree.fromstring(metadata_contents)
rating = node.xpath('//t:rating/text()', namespaces = {'t':'http://example/namespace'})
>>> rating
['PG']

How would I get the value "au-oflc" ?

like image 917
David542 Avatar asked Aug 25 '26 11:08

David542


2 Answers

You need to retrieve the node itself, not its text:

rating = node.xpath('//t:rating', namespaces = {'t':'http://example/namespace'})
print rating[0].attrib['system']
like image 144
georg Avatar answered Aug 27 '26 02:08

georg


georg's answer assumes all rating elements will have a system tag. if that is not necessarily the case, using rating[0].attrib.get('system') will avoid a KeyError.

like image 40
jcomeau_ictx Avatar answered Aug 27 '26 01:08

jcomeau_ictx



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!