首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ElementTree在XML树中查找元素

使用ElementTree在XML树中查找元素
EN

Stack Overflow用户
提问于 2014-01-15 08:48:17
回答 1查看 356关注 0票数 1

我正在尝试使用ElementTree定位XML文件中的特定元素。下面是XML:

代码语言:javascript
复制
<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>项目很感兴趣。下面是我使用的代码:

代码语言:javascript
复制
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表达式,但是我被难住了--我找不到元素。有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2014-01-15 09:15:11

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

下面的代码应该可以工作:

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21127119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档