parsing xml using python elements

I think I understand you know. Try this:

import xml.etree.ElementTree as ET

failure = """[your xml above]"""

doc = ET.fromstring(failure)
for f in doc.findall('.//testcase[failure]'):
     print(f.attrib['name'])

Output:

featTest
featuTest

Edit:

To extract the attribute values of the name attribute of test cases which did NOT fail, try this:

for f in doc.findall('.//testcase'):
    if not f.findall('.//failure'):
        print(f.attrib['name'])    

Output:

savTest
feaTest
quiest

Just FYI, the support of ElementTree for xpath is quite limited. If available to you, use lxml for that purpose. As you’ll see below, it’s much simpler, because the version of xpath supported by lxml includes the function not():

from lxml import etree
ldoc = etree.XML(failure.encode())
for case in ldoc.xpath('//testcase[not(failure)]/@name'):
    print(case)

Same output as above.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top