Parse XML namespace with Element Tree findall


How can I use a query element tree findall('Email') given the following xml?

<DocuSignEnvelopeInformation xmlns:xsd="" xmlns:xsi="" xmlns="">
                <Email>[email protected]</Email>
                <UserName>Joe Shmoe</UserName>

I have a feeling it has to do with the namespace but I’m not sure. I looked at the docs and had no luck.

tree = <xml.etree.ElementTree.ElementTree object at 0x7f27a47c4fd0>
root = tree.getroot()
<Element '{}DocuSignEnvelopeInformation' at 0x7f27a47b8a48>



You should read the docs more closely, in particular the section on Parsing XML with Namespaces, which includes an example that is almost exactly what you want.

But even without the docs, the answer is actually contained in your example output. When you printed the root element of your document…

>>> tree = etree.parse(open('data.xml'))
>>> root = tree.getroot()
>>> root
<Element {}DocuSignEnvelopeInformation at 0x7f972cd079e0>

…you can see that it printed the root element name (DocuSignEnvelopeInformation) with a namespace prefix ({}). You can use this same prefix as part of your argument to findall:

>>> root.findall('{}Email')

But this by itself won’t work, since this would only find Email elements that are immediate children of the root element. You need to provide an ElementPath expression to cause findall to perform a search of the entire document. This works:

>>> root.findall('.//{}Email')
[<Element {}Email at 0x7f972949a6c8>]

You can also perform a similar search using XPath and namespace prefixes, like this:

>>> root.xpath('//docusign:Email',
... namespaces={'docusign': ''})
[<Element {}Email at 0x7f972949a6c8>]

This lets you use XML-like namespace: prefixes instead of the LXML namespace syntax.

Answered By – larsks

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published