【问题标题】:Find an element in an XML tree using ElementTree使用 ElementTree 在 XML 树中查找元素
【发布时间】:2014-01-15 00:48:16
【问题描述】:

我正在尝试使用 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>

我对@9​​87654322@ 项目感兴趣。这是我正在使用的代码:

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 表达式,但我很难过 - 我找不到元素。有什么建议吗?

【问题讨论】:

  • 您的 XML 文档看起来很奇怪。看来第二行 &lt;?version... 应该是第一行。

标签: python xpath elementtree


【解决方案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

【讨论】:

    猜你喜欢
    • 2013-05-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多