Parsing an XML using ElementTree: The root of the tree is returned as an XML itself. How do I further parse it to find an element?

Viewed 131

I'm parsing an XML file using ElementTree. In my case, the root of the tree is returned as an XML itself. How do I further parse it to extract the text inside the element <a:Message>?

tree = ETree.ElementTree(response)
print("tree:---", tree)
print("root:---", tree.getroot())
print("element found:---", tree.getroot().findall("./a:Message"))

Output

    tree:--- <xml.etree.ElementTree.ElementTree object at 0x00000>
    root:--- <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
        <s:Header>
            <o:Security s:mustUnderstand="1"
                        xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                <!-- Sample XML -->
            
            </o:Security>
        </s:Header>
        <s:Body>
            <Response xmlns="http://tempuri.org/">
                <Result xmlns:a="http://xmldataschemas.data">
                    <!-- Fields must be in this exact order.  -->
                    <a:Message>xxx Document is being processed</a:Message>
                    <a:ResponseCode>DOCUMENT_ERROR</a:ResponseCode>
                </Result>
            </Response>
        </s:Body>
    </s:Envelope>
     element found:--- None
1 Answers

You have to deal with the namespaces in your xml. So try this instead:

ns = {'a': 'http://xmldataschemas.data'}
root.find('.//a:Message',ns).text

Output:

'xxx Document is being processed'
Related