Parsing a field from SOAP response in Python using LXML

Viewed 218

I want to parse the customer_id from a SOAP response. Here is the XML:

<?xml version='1.0' encoding='UTF-8'?>
<soap11env:Envelope xmlns:s1="myservice.mymodels.models" xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="me.web.3.5.4.0">
    <soap11env:Body>
        <tns:orderResponse>
            <tns:orderResult>
                <s1:customer_id>12345</s1:customer_id>
            </tns:orderResult>
        </tns:orderResponse>
    </soap11env:Body>
</soap11env:Envelope>

This is a piece a cake with BeautifulSoap....but I am restricted to LXML. Nothing I have tried with LXML has worked.

With my latest attempt, I tried getting the root element, then go from there:

tree = etree.fromstring(response.content)
root = tree.getroot()

But I get the following error:

'lxml.etree._Element' object has no attribute 'getroot'

How can I just get the customer_id from this XML?

1 Answers

It's also simple with lxml; you just have to watch your namespaces... first:

doc = etree.XML(response.text.encode())

then, with namespaces:

ns = {"xx":"myservice.mymodels.models"}
target =  doc.xpath('//xx:customer_id',namespaces=ns)[0]
target.text

or, if you don't want to bother with namespaces

target = doc.xpath('//*[local-name()="customer_id"]')[0]
target.text

In both cases, the output is:

'12345'
Related