Python3 xml, как мне найти этот элемент xml без пространства имен? - PullRequest
0 голосов
/ 19 декабря 2018

Когда следующий текст загружен в ElementTree Element, метод 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?

1 Ответ

0 голосов
/ 19 декабря 2018

Поскольку вы ищете только faultstring, который является прямым потомком корневого элемента Envelope:

ele = xml.find('faultstring')

Чтобы найти элемент в любом месте в данном элементеконтекст, который вы можете использовать .//element_name:

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

Для справки: ElementTree: поддерживаемый синтаксис XPath

...