使用ElementTree解析XML:树的根作为XML本身返回.如何进一步解析它以查找元素



我正在使用ElementTree解析一个XML文件。在我的例子中,树的根作为XML本身返回。我如何进一步解析它以提取元素<a: 消息>?

tree = ETree.ElementTree(response)
print("tree:---", tree)
print("root:---", tree.getroot())
print("element found:---", tree.getroot().findall("./a:Message"))

输出

tree:--- <xml.etree.ElementTree.ElementTree object at 0x00000>
root:--- <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<o:Security s:mustUnderstand="1"
xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<!-- Sample XML -->

</o:Security>
</s:Header>
<s:Body>
<Response xmlns="http://tempuri.org/">
<Result xmlns:a="http://xmldataschemas.data">
<!-- Fields must be in this exact order.  -->
<a:Message>xxx Document is being processed</a:Message>
<a:ResponseCode>DOCUMENT_ERROR</a:ResponseCode>
</Result>
</Response>
</s:Body>
</s:Envelope>
element found:--- None

您必须处理xml中的名称空间。所以试试这个:

ns = {'a': 'http://xmldataschemas.data'}
root.find('.//a:Message',ns).text

输出:

'xxx Document is being processed'

相关内容

最新更新