我正在使用 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'
我可以解析 XML 文档并找到“事件”节点
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 只返回空列表,它无法再定位“事件”节点。我还尝试注册这些 namespace ,例如:
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 中很重要。
