使用 Python-elementree 解析 XML
Parsing XML using Python-elementree
我正在使用 python 中的 ElementTree 库来解析 XML 但无法提取字段。
解析示例XML如下所示。
这里我要检查失败并打印相应的测试用例名称。
从下面的示例中,我需要将输出作为 featTest 和 featuTest
<?xml version='1.0' encoding='UTF-8' ?>
<testsuite name="" tests="5" failures="1" flakes="1" errors="0" skipped="0" time="339.777" hostname="localhost">
<testcase name="featTest" classname="test.urlOpenState.id" time="25.874">
<failure>java.lang.RuntimeException:
</failure>
</testcase>
<testcase name="savTest" classname="com.State.id" time="2.886" />
<testcase name="featuTest" classname="test.urlte.id" time="24.171" flaky="true">
<failure>java.lang.RuntimeException:
</failure>
</testcase>
<testcase name="feaTest" classname="test.urlte.id" time="4.645" />
<testcase name="quiest" classname="test.urls.id" time="9.008" />
</testsuite>
link 指导或任何建议都会有所帮助。
我想我明白你知道的。试试这个:
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'])
输出:
featTest
featuTest
编辑:
要提取未失败的测试用例的 name
属性的属性值,试试这个:
for f in doc.findall('.//testcase'):
if not f.findall('.//failure'):
print(f.attrib['name'])
输出:
savTest
feaTest
quiest
仅供参考,ElementTree 对 xpath 的支持非常有限。如果可用,请为此目的使用 lxml。正如您将在下面看到的,它要简单得多,因为 lxml 支持的 xpath 版本包括函数 not()
:
from lxml import etree
ldoc = etree.XML(failure.encode())
for case in ldoc.xpath('//testcase[not(failure)]/@name'):
print(case)
与上面相同的输出。
我正在使用 python 中的 ElementTree 库来解析 XML 但无法提取字段。
解析示例XML如下所示。
这里我要检查失败并打印相应的测试用例名称。
从下面的示例中,我需要将输出作为 featTest 和 featuTest
<?xml version='1.0' encoding='UTF-8' ?>
<testsuite name="" tests="5" failures="1" flakes="1" errors="0" skipped="0" time="339.777" hostname="localhost">
<testcase name="featTest" classname="test.urlOpenState.id" time="25.874">
<failure>java.lang.RuntimeException:
</failure>
</testcase>
<testcase name="savTest" classname="com.State.id" time="2.886" />
<testcase name="featuTest" classname="test.urlte.id" time="24.171" flaky="true">
<failure>java.lang.RuntimeException:
</failure>
</testcase>
<testcase name="feaTest" classname="test.urlte.id" time="4.645" />
<testcase name="quiest" classname="test.urls.id" time="9.008" />
</testsuite>
link 指导或任何建议都会有所帮助。
我想我明白你知道的。试试这个:
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'])
输出:
featTest
featuTest
编辑:
要提取未失败的测试用例的 name
属性的属性值,试试这个:
for f in doc.findall('.//testcase'):
if not f.findall('.//failure'):
print(f.attrib['name'])
输出:
savTest
feaTest
quiest
仅供参考,ElementTree 对 xpath 的支持非常有限。如果可用,请为此目的使用 lxml。正如您将在下面看到的,它要简单得多,因为 lxml 支持的 xpath 版本包括函数 not()
:
from lxml import etree
ldoc = etree.XML(failure.encode())
for case in ldoc.xpath('//testcase[not(failure)]/@name'):
print(case)
与上面相同的输出。