pLumo
pLumo

Reputation: 407

Get localname from attribute in lxml

Question:

I can get element.tag name without namespace using lxml.etree.QName(element).localname.
How to do similar with element.attrib ?


Example:

Assuming this XML file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root xmlns="some_ns" xmlns:soc="some_other_ns" >
    <someTag attr1="something" soc:attr2="something else"></someTag>
</root>

This script returns attrib with namespace for the second attribute:

from lxml import etree
root = etree.parse('test.xml').getroot()
ns = { 'n':'some_ns', 'son':'some_other_ns' }
print ([e.attrib for e in root.xpath('./n:someTag', namespaces = ns)])

Output:

[{'{some_other_ns}attr2': 'something else', 'attr1': 'something'}]

Upvotes: 2

Views: 2485

Answers (2)

pLumo
pLumo

Reputation: 407

Thanks to @mzjn's answer, I could write a function that outputs the attributes as dict like e.attrib does.

from lxml import etree
root = etree.parse('test.xml').getroot()
ns = { 'n':'some_ns', 'son':'some_other_ns' }

def attrib_localnames(a):
    out={}
    for n,v in a.attrib.items():
        out[etree.QName(n).localname]=v
    return out

print ([attrib_localnames(e) for e in root.xpath('./n:someTag', namespaces = ns)])

Output:

[{'attr1': 'something', 'attr2': 'something else'}]

Upvotes: 0

mzjn
mzjn

Reputation: 51052

You can use QName for attributes too.

tag = root.xpath('./n:someTag', namespaces = ns)[0]
for a, v in tag.attrib.items():
    print(etree.QName(a).localname, v)

Output:

attr1 something
attr2 something else

Upvotes: 1

Related Questions