Python3 xml,如何找到这个非命名空间 xml 元素?

Python3 xml, how can I find this non-namespace xml element?

当以下文本加载到 ElementTree 元素时,find 方法无法找到没有分配命名空间的元素之一。

import xml.etree.ElementTree as ElementTree

xml_text = """
<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope/"><ns0:Body><ns0:Fault><faultcode>a:ActionNotSupported</faultcode><faultstring xml:lang="en-US">The message with Action \'\' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</faultstring></ns0:Fault></ns0:Body></ns0:Envelope>
"""

xml = ElementTree.fromstring(xml_text)
ele = xml.find('faultstring')
ele == None #True

如何找到 faultstring 元素?

因为您只查找根元素 Envelope 的直接子元素 faultstring :

ele = xml.find('faultstring')

要在给定元素上下文中任意位置查找元素,您可以使用.//element_name :

ele = xml.find('.//faultstring')

供参考:ElementTree: Supported XPath syntax