使用ElementTree在XML树中查找元素 [英] Find an element in an XML tree using ElementTree

查看:42
本文介绍了使用ElementTree在XML树中查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

我对< Created> 项目。这是我使用的代码:

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

我尝试了很多不同的XPath表达式,但是我我很困惑-我找不到该元素。

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

推荐答案

您没有引用XML文档中存在的命名空间,因此ElementTree找不到元素在那个XPath中。 您需要告诉ElementTree您正在使用什么名称空间。

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.

以下应该起作用:

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围绕着ElementTree进行了包装,并且对命名空间提供了良好的支持,而不必担心字符串格式

这篇关于使用ElementTree在XML树中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆