[英]Trying to check if a tag exists in XML before parsing
在解析之前,我需要檢查 XML 文件中是否存在某些標簽; 我在 Python 中使用元素樹。 讀到這里,我試着寫這個:
tgz_xml = f"https://www.ncbi.nlm.nih.gov/pmc/utils/oa/oa.fcgi?id=PMC8300416"
response = urllib.request.urlopen(tgz_xml).read()
tree = ET.fromstring(response)
for OA in tree.findall('OA'):
records = OA.find('records')
if records is None:
print('records missing')
else:
print('records found')
我需要檢查“記錄”標簽是否存在。 我沒有收到錯誤,但這不會打印出任何東西。 我做錯了什么? 謝謝!
解析此 XML 文檔變量tree
時已經指向元素OA
,因此在搜索此元素時,表達式tree.findall('OA')
返回一個空列表並且不執行循環。 刪除該行並執行代碼:
import xml.etree.ElementTree as ET
from urllib.request import urlopen
tgz_xml = f"https://www.ncbi.nlm.nih.gov/pmc/utils/oa/oa.fcgi?id=PMC8300416"
with urlopen(tgz_xml) as conn:
response = conn.read()
tree = ET.fromstring(response)
records = tree.find('records')
if records is None:
print('records missing')
else:
print('records found')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.