在ElementTree/Python中使用多个属性查找出现次数
我有以下的XML内容。
<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="10" failures="0" disabled="0" errors="0" time="0.001" name="AllTests">
<testsuite name="TestOne" tests="5" failures="0" disabled="0" errors="0" time="0.001">
<testcase name="DefaultConstructor" status="run" time="0" classname="TestOne" />
<testcase name="DefaultDestructor" status="run" time="0" classname="TestOne" />
<testcase name="VHDL_EMIT_Passthrough" status="run" time="0" classname="TestOne" />
<testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" />
<testcase name="VHDL_SIMULATE_Passthrough" status="run" time="0.001" classname="TestOne" />
</testsuite>
</testsuites>
问:我该如何找到这个节点 <testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" />
?我发现有一个函数叫 tree.find()
,但是这个函数的参数似乎是元素的名称。
我需要根据属性来找到这个节点:name = "VHDL_BUILD_Passthrough" AND classname="TestOne"
。
2 个回答
0
你需要逐个查看你拥有的 <testcase />
元素,像这样:
from xml.etree import cElementTree as ET
# assume xmlstr contains the xml string as above
# (after being fixed and validated)
testsuites = ET.fromstring(xmlstr)
testsuite = testsuites.find('testsuite')
for testcase in testsuite.findall('testcase'):
if testcase.get('name') == 'VHDL_BUILD_Passthrough':
# do what you will with `testcase`, now it is the element
# with the sought-after attribute
print repr(testcase)
24
这要看你使用的版本。如果你有 ElementTree 1.3 及以上版本(包括 Python 2.7 的标准库),你可以使用基本的 xpath 表达式,正如文档中所描述的,比如 [@attrib='value']
:
x = ElmentTree(file='testdata.xml')
cases = x.findall(".//testcase[@name='VHDL_BUILD_Passthrough'][@classname='TestOne']")
不过,如果你使用的是早期版本的 ElementTree(1.2,包含在 Python 2.5 和 2.6 的标准库中),那么就不能享受这个方便的功能,你需要自己进行过滤。
x = ElmentTree(file='testdata.xml')
allcases = x12.findall(".//testcase")
cases = [c for c in allcases if c.get('classname') == 'TestOne' and c.get('name') == 'VHDL_BUILD_Passthrough']