在ElementTree/Python中使用多个属性查找事件

pro*_*eek 9 python xml elementtree

我有以下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>
Run Code Online (Sandbox Code Playgroud)

问:我如何找到节点<testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" />?我找到了该函数tree.find(),但该函数的参数似乎是元素名称.

我需要根据属性找到节点:name = "VHDL_BUILD_Passthrough" AND classname="TestOne".

chm*_*lig 20

这取决于您使用的版本.如果您有ElementTree 1.3+(包括在Python 2.7标准库中),您可以使用基本的xpath表达式,如文档中所述,如[@attrib='value']:

x = ElmentTree(file='testdata.xml')
cases = x.findall(".//testcase[@name='VHDL_BUILD_Passthrough'][@classname='TestOne']")
Run Code Online (Sandbox Code Playgroud)

不幸的是,如果您使用的是早期版本的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']
Run Code Online (Sandbox Code Playgroud)