如何使用 python 中的 ElementTree 正确检查 xml 树中的元素?

How to correctly check for an element in a xml tree with ElementTree in python?

我有以下xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error>
    <displayMessage>Authentication Error</displayMessage>
    <message>Authentication Error: org.somewhere.auth.AuthenticationException: Invalid username or password
</message>
    <code>2</code>
</error>

我正在尝试检查 Authentication Error 元素是否存在于 error 下。但只需使用以下代码

import requests
from xml.etree import ElementTree


r = requests.get(....)
root = ElementTree.fromstring(r.text)
print(root.findall('error'))

它returns一个空列表,我不明白。我希望得到一个元素,因为 xml 中有一个 error 元素。

我正要尝试类似

的东西
if len(root.findall('error//Authentication Error'))>0:
    print("auth error")
    ...

如何正确操作?

在 xmlstring 中查找消息标签

r = requests.get(....)
root = ElementTree.fromstring(r.text)

if len([s.text for s in root.findall(".//message") if 'Authentication Error' in s.text ])>0:
   print("auth error")
   ...

因为errorroot

尝试打印出 root: <Element 'error' at 0x7f898462ff98>.

所以你可以找到 displayMessage 然后检查它的文本:

any(item.text == "Authentication Error" for item in root.findall("displayMessage"))

它会 return True 如果至少有一个 Authentication Error.