1

I am trying to locate a specific element in an XML file, using ElementTree. Here is the XML:

<documentRoot>
    <?version="1.0" encoding="UTF-8" standalone="yes"?>
    <n:CallFinished xmlns="http://api.callfire.com/data" xmlns:n="http://api.callfire.com/notification/xsd">
        <n:SubscriptionId>96763001</n:SubscriptionId>
        <Call id="158864460001">
            <FromNumber>5129618605</FromNumber>
            <ToNumber>15122537666</ToNumber>
            <State>FINISHED</State>
            <ContactId>125069153001</ContactId>
            <Inbound>true</Inbound>
            <Created>2014-01-15T00:15:05Z</Created>
            <Modified>2014-01-15T00:15:18Z</Modified>
            <FinalResult>LA</FinalResult>
            <CallRecord id="94732950001">
                <Result>LA</Result>
                <FinishTime>2014-01-15T00:15:15Z</FinishTime>
                <BilledAmount>1.0</BilledAmount>
                <AnswerTime>2014-01-15T00:15:06Z</AnswerTime>
                <Duration>9</Duration>
            </CallRecord>
        </Call>
    </n:CallFinished>
</documentRoot>

I am interested in the <Created> item. Here is the code I am using:

import xml.etree.ElementTree as ET

calls_root = ET.fromstring(calls_xml)
    for item in calls_root.find('CallFinished/Call/Created'):
        print "Found you!"
        call_start = item.text

I have tried a bunch of different XPath expressions, but I'm stumped - I cannot locate the element. Any tips?

1 Answers1

1

You aren't referencing the namespaces that exist in the XML document, so ElementTree can't find the elements in that XPath. You need to tell ElementTree what namespaces you are using.

The following should work:

import xml.etree.ElementTree as ET

namespaces = {'n':'{http://api.callfire.com/notification/xsd}',
             '_':'{http://api.callfire.com/data}'
            }
calls_root = ET.fromstring(calls_xml)
    for item in calls_root.find('{n}CallFinished/{_}Call/{_}Created'.format(**namespaces)):
        print "Found you!"
        call_start = item.text

Alternatively, LXML has a wrapper around ElementTree and has good support for namespaces without having to worry about string formatting.