开发者

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开发者_StackOverflow" />
    <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".


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']


You'll have to iterate through the <testcase /> elements that you have, like so:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜