![](/img/trans.png)
[英]Using untangle, how can I check the existence of attributes and tags in XML before parsing
[英]How can I check the existence of attributes and tags in XML before parsing?
我正在python中通過Element Tree解析XML文件,並將內容寫入cpp文件。
子標簽的內容對於不同的標簽將是不同的。 例如,第一個事件標記將party標記作為子標記但第二個事件標記沒有。
- >如何在解析之前檢查標簽是否存在?
- > Children在第一個事件標記中有value屬性,但在第二個事件標記中沒有。 如何在獲取屬性之前檢查屬性是否存在。
- >目前我的代碼為非現有的party標簽拋出了一個錯誤,並為第二個children標簽設置了“None”屬性值。
<main>
<event>
<party>Big</party>
<children type="me" value="3"/>
</event>
<event>
<children type="me"/>
</event>
</main>
碼:
import xml.etree.ElementTree as ET
tree = ET.parse('party.xml')
root = tree.getroot()
for event in root.findall('event'):
parties = event.find('party').text
children = event.get('value')
我想檢查標簽然后取其值。
如果標簽不存在, .find()
確實返回None
。 只需測試該值:
for event in root.findall('event'):
party = event.find('party')
if party is None:
continue
parties = party.text
children = event.get('value')
您已經在事件上使用.get()
來測試屬性的value
; 如果該屬性不存在,它也返回None
。
屬性存儲在.attrib
字典中,因此您也可以使用標准Python技術來顯式測試該屬性:
if 'value' in event.attrib:
# value attribute is present.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.