Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find occurrence using multiple attributes in ElementTree/Python

I have the following 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>

Q : How can I find the node <testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" />? I find the function tree.find(), but the parameter to this function seems element name.

I need to find the node based on attribute : name = "VHDL_BUILD_Passthrough" AND classname="TestOne".

like image 231
prosseek Avatar asked Jan 26 '11 19:01

prosseek


1 Answers

This depends on what version you're using. If you have ElementTree 1.3+ (including in Python 2.7 standard library) you can use a basic xpath expression, as described in the docs, like [@attrib='value']:

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

Unfortunately if you're using an earlier version of ElementTree (1.2, included in standard library for python 2.5 and 2.6) you can't use that convenience and need to filter yourself.

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']
like image 125
chmullig Avatar answered Oct 29 '22 05:10

chmullig