[英]getchildren removed for python 3.9
我讀到以下內容:“自 3.2 版以來已棄用,將在 3.9 版中刪除:使用 list(elem) 或迭代。” ( https://docs.python.org/3.8/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren )
我的代碼適用於 python 3.8 及以下版本:
tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.getchildren()[0].attrib['ID'])
但是,當我嘗試為 python 3.9 更新它時,我無法
tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.list(elem)[0].attrib['ID'])
我收到以下錯誤AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'list'
“使用list(elem)
或迭代”的字面意思是list(root)
,而不是root.list()
。 以下將起作用:
getID = list(root)[0].attrib['ID']
您可以將任何可迭代對象包裝在列表中,棄用說明特別告訴您root
是可迭代的。 由於只為一個元素分配一個列表是相當低效的,因此您可以獲取迭代器並從中提取第一個元素:
getID = next(iter(root)).attrib['ID']
這是一個更緊湊的符號
for child in root:
getID = child.attrib['ID']
break
主要區別在於當沒有孩子時(直接由next
vs 當您嘗試訪問不存在的getID
變量時)將引發錯誤。
錯誤表明您應該這樣寫:
getID = list(root)[0].attrib['ID']
調用list
遍歷root
元素並為其提供子元素,同時將其轉換為可以索引的列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.