簡體   English   中英

如何使用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'))

它返回一個空列表,我不明白。 我希望得到一個元素,因為xml中有一個error元素。

我正要嘗試類似

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

怎么做對?

這是因為該errorroot

嘗試輸出root<Element 'error' at 0x7f898462ff98>

因此,您可以找到displayMessage ,然后檢查其文本:

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

如果存在至少一個Authentication Error ,它將返回True

在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")
   ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM