[英]Parsing an XML using ElementTree: The root of the tree is returned as an XML itself. How do I further parse it to find an element?
我正在使用 ElementTree 解析 XML 文件。 在我的情况下,树的根返回为 XML 本身。 如何进一步解析它以提取元素 <a:Message> 中的文本?
tree = ETree.ElementTree(response)
print("tree:---", tree)
print("root:---", tree.getroot())
print("element found:---", tree.getroot().findall("./a:Message"))
Output
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
Output:
'xxx Document is being processed'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.