[英]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.