这是一个使用xml.etree.ElementTree
库和index()
方法的解决方案:
import xml.etree.ElementTree as ET
xml_str = '''<?xml version="1.0" encoding="utf-8"?>
<components version="1.0.0">
<component type="foo">
<maintag>
<subtag>
<check>Foo</check>
</subtag>
<subtag>
<check></check>
</subtag>
<subtag>
</subtag>
</maintag>
</component>
</components>
'''
root = ET.fromstring(xml_str)
def check_subtag(elem):
if len(elem) == 0:
print(f"错误:第{root.findall('.//subtag').index(elem)}个子标签没有子标签(例如:<check>)")
if len(elem) != 0:
for c in elem.iter():
if c.tag == "check" and c.text is not None:
print(f"正确:第{root.findall('.//subtag').index(elem)}个子标签含有文本为{c.text}的<check>标签")
if c.tag == "check" and c.text is None:
print(f"错误:第{root.findall('.//subtag').index(elem)}个子标签含有空的<check>标签")
for subtag in root.findall(".//subtag"):
check_subtag(subtag)
输出结果:
正确:第0个子标签含有文本为Foo的<check>标签
错误:第1个子标签含有空的<check>标签
错误:第2个子标签没有子标签(例如:<check>)
或者通过返回错误代码的方式:
import xml.etree.ElementTree as ET
xml_str = '''<?xml version="1.0" encoding="utf-8"?>
<components version="1.0.0">
<component type="foo">
<maintag>
<subtag>
<check>Foo</check>
</subtag>
<subtag>
<check></check>
</subtag>
<subtag>
</subtag>
<subtag>
<check> </check>
</subtag>
</maintag>
</component>
</components>
'''
root = ET.fromstring(xml_str)
def check_subtag(elem):
# 错误代码:
# 0 - 正确,<check>存在且包含文本或空格
# 1 - 错误,<check>存在但无文本
# 2 - 错误,<check>不存在
if len(elem) == 0:
return 2
if len(elem) != 0:
for c in elem.iter():
if c.tag == "check" and c.text is not None:
return 0
if c.tag == "check" and c.text is None:
return 1
for subtag in root.findall(".//subtag"):
if check_subtag(subtag) != 0:
print(f"子标签位于第{root.findall('.//subtag').index(subtag)}的位置,错误代码为{check_subtag(subtag)}")
输出结果:
子标签位于第1的位置,错误代码为1
子标签位于第2的位置,错误代码为2