Python 2.5 ElementTree句柄xml节点,名称为

2024-04-25 22:45:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python2.5,elementtree1.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>

在我注册名称空间之后

^{pr2}$

我可以解析XMLdocument并找到“event”节点

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">

在芬德尔树只返回空列表,并且无法再定位“event”节点。我还尝试注册这些名称空间,例如:

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'

但没用。在

我只能使用python2.5和elementtree1.2(不能使用lxml)。有人知道如何定位“CHMasterbook”具有这些名称空间的“event”节点吗?在


Tags: 名称comeventhttpmessage节点www空间
1条回答
网友
1楼 · 发布于 2024-04-25 22:45:20

试试这个:

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中很重要。在

相关问题 更多 >