使用ElementTree在XML树中查找元素

时间:2014-01-15 00:48:17

标签: python xpath elementtree

我正在尝试使用ElementTree在XML文件中找到特定元素。这是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>

我对<Created>项感兴趣。这是我正在使用的代码:

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

我尝试了一堆不同的XPath表达式,但是我很难过 - 我无法找到该元素。有什么提示吗?

1 个答案:

答案 0 :(得分:1)

您没有引用XML文档中存在的命名空间,因此ElementTree无法在该XPath中找到元素。 You need to tell ElementTree what namespaces you are using.

以下内容应该有效:

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

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