Parsing XML root attributes

Wednesday, May 27, 2009

Imagine you want to read the attribute test= from this fragment of XML called test.xml:

<widget test="foo">
    <name>blah</name>
</widget>

Using lxml, you need to run getroot.

import lxml.etree as etree
tree = etree.parse("test.xml")
print(tree.getroot().attrib['test'])