2016-11-09 109 views
0

我在python3中使用ElementTree XML API並且有一個問題,這似乎很基礎,我只是沒有在文檔中找到正確的函數它。起點是我認爲一個xml文件,其名稱在字符串name中給出。我正在尋找一個函數來檢查一個chld是否存在。由它的名字。目前,我在做什麼是:在python中檢查是否存在使用ElementTree進行XML解析的孩子

 import xml.etree.ElementTree as ET 
    tree = ET.parse(name) 
    root = tree.getroot() 
    item = root.getchildren()[2] 

,因爲我知道,我期待在該項目是在位置2(第3項)。但我寧願有這樣的事情:

 item = root.checkIfExists('itemName') 

有人可以爲此提出一個函數嗎?或者更好的方法來解決這個問題?謝謝。

回答

2

引用the documentation

Element.findall()發現僅與一標籤,其是當前元素的直接子元素。 Element.find()找到的第一個孩子帶有特定標記

所以,儘量:

item = root.find('itemName') 

.find()回報None,如果沒有這樣的元素存在。 .findall()在這種情況下返回空列表。

示範:

import xml.etree.ElementTree as ET 
root = ET.XML('<root><item1/><item2/><itemName/></root>') 
assert root.getchildren()[2] is root.find('itemName')