在 python 中使用 ElementTree 进行 XML 解析时检查子项是否存在
Checking for the existence of children when using ElementTree for XML parsing in python
我在 python3 中使用 ElementTree XML API 并且有一个问题,这似乎是基本的,我只是没有在文档中找到正确的功能来做它。起点是我考虑一个 xml 文件,其名称在字符串 name
中给出。我正在寻找一个检查 chld 是否存在的函数。通过它的名字。目前我正在做的是:
import xml.etree.ElementTree as ET
tree = ET.parse(name)
root = tree.getroot()
item = root.getchildren()[2]
因为我知道我要查找的项目在位置 2(第 3 个条目)。但我宁愿有这样的东西:
item = root.checkIfExists('itemName')
有人可以为此建议一个功能吗?或者更好的方法来解决这个问题?谢谢。
Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag
所以,尝试:
item = root.find('itemName')
.find()
returns None
如果不存在这样的元素。 .findall()
returns 在这种情况下是一个空列表。
示范:
import xml.etree.ElementTree as ET
root = ET.XML('<root><item1/><item2/><itemName/></root>')
assert root.getchildren()[2] is root.find('itemName')
我在 python3 中使用 ElementTree XML API 并且有一个问题,这似乎是基本的,我只是没有在文档中找到正确的功能来做它。起点是我考虑一个 xml 文件,其名称在字符串 name
中给出。我正在寻找一个检查 chld 是否存在的函数。通过它的名字。目前我正在做的是:
import xml.etree.ElementTree as ET
tree = ET.parse(name)
root = tree.getroot()
item = root.getchildren()[2]
因为我知道我要查找的项目在位置 2(第 3 个条目)。但我宁愿有这样的东西:
item = root.checkIfExists('itemName')
有人可以为此建议一个功能吗?或者更好的方法来解决这个问题?谢谢。
Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag
所以,尝试:
item = root.find('itemName')
.find()
returns None
如果不存在这样的元素。 .findall()
returns 在这种情况下是一个空列表。
示范:
import xml.etree.ElementTree as ET
root = ET.XML('<root><item1/><item2/><itemName/></root>')
assert root.getchildren()[2] is root.find('itemName')