Find an element in an XML tree using ElementTree

只谈情不闲聊 提交于 2020-01-06 04:25:54

问题


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:


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.



来源:https://stackoverflow.com/questions/21127119/find-an-element-in-an-xml-tree-using-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!