簡體   English   中英

Python 2.5 ElementTree處理帶有名稱空間的xml節點

[英]Python 2.5 ElementTree handle xml node with namespace

我正在使用Python2.5,ElementTree 1.2來解析XML文檔,如下所示:

<cm:CompositeMessage xmlns:cm="http://www.xyz.com">
    <cm:Message>
        <cm:Body format="text/xml">
            <CHMasterbook >
                    <event>
                            <eventName>Snapshot</eventName>
                            <date>2013-10-25</date>
                            <time>20:59:02</time>
                    </event>
            </CHMasterbook>
         </cm:Body>
     </cm:Message>
</cm:CompositeMessage>

注冊名稱空間后

ET._namespace_map['http://www.xyz.com'] = 'cm'

我可以解析XMLdocument並找到“事件”節點

tree = ElementTree(fromstring(xml))
tree.findall('./{http://www.xyz.com}Message/{http://www.xyz.com}Body/CHMasterBook/event')

但是,如果“ CHMasterbook”節點具有類似

<CHMasterbook xmlns="http://uri.xyz.com/Chorus/Message" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://uri.xyz.com/Chorus/Message ../schema/chorus-master-book-msg.xsd">

tree.findall僅返回空列表,並且無法再找到“事件”節點。 我還嘗試注冊這些名稱空間,例如:

ET._namespace_map['http://uri.xyz.com/Chorus/Message'] = 'xmlns'
ET._namespace_map['http://www.w3.org/2001/XMLSchema-instance'] = 'xmlns:xsi'
ET._namespace_map['http://uri.xyz.com/Chorus/Message ../schema/chorus-master-book-msg.xsd'] = 'xsi:schemaLocationi'

但這沒有幫助。

我只能使用Python 2.5和ElementTree 1.2(不能使用lxml)。 有誰知道如何使用具有這些命名空間的“ CHMasterbook”來定位“事件”節點?

嘗試這個:

tree = ElementTree(fromstring(xml))
tree.findall('./{http://www.xyz.com}Message'
             '/{http://www.xyz.com}Body'
             '/{http://uri.xyz.com/Chorus/Message}CHMasterbook'
             '/{http://uri.xyz.com/Chorus/Message}event')

在您的示例中,您使用CHMasterbook ,有時使用CHMasterBook 記住大小寫在XML中很重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM