Python的xml.dom.minidom中的getElementsByTagName()不起作用

时间:2015-03-24 14:14:25

标签: python xml dom minidom

我正在解析从gtest生成的输出XML文件。我想找到每个测试用例的结果。测试用例仅在" testcase"有元素"失败"否则测试用例通过。但我无法访问元素。

我的xml文件: -

<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="11" failures="0" disabled="0" errors="0" timestamp="2015-03-23T17:29:43" time="1.309" name="AllTests">
  <testsuite name="AAA" tests="4" failures="0" disabled="0" errors="0" time="0.008">
    <testcase name="BBBB" status="run" time="0.002" classname="AAA" />
      <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type="" />
    <testcase name="CCC" status="run" time="0.002" classname="AAA" />
    <testcase name="DDD" status="run" time="0.002" classname="AAA" />
    <testcase name="FFF" status="run" time="0.002" classname="AAA" />
  </testsuite>
</testsuites>

我的python文件是: -

from xlrd import open_workbook
from xml.dom.minidom import parse
import xml.dom.minidom

# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse("output.xml")
testsuites = DOMTree.documentElement 
testCaseCollection = testsuites.getElementsByTagName("testcase")
testCasefailure = testsuites.getElementsByTagName("failure")

OutputXLS = open_workbook('output.xls')

for testCase in testCaseCollection:

        #print testCase.firstChild;
        if testsuites.getElementsByTagName("failure"):
                print testCase.getAttribute("name"), " --> ","FAIL"
        else:
                print testCase.getAttribute("name"), " --> ","PASS"

输出是: -

BBB -->  PASS
CCC  -->  PASS
DDD  -->  PASS
FFF  -->  PASS

虽然测试用例&#34; BBB&#34;失败,因为它已经失败&#34;在xml中的属性,它显示传递结果。 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

from xlrd import open_workbook
from xml.dom.minidom import parse

# Open XML document using minidom parser
DOMTree = parse("output.xml")
testsuites = DOMTree.documentElement 
testCaseCollection = testsuites.getElementsByTagName("testcase")

OutputXLS = open_workbook('output.xls')

for testCase in testCaseCollection:
    sibNode = testCase.nextSibling.nextSibling
    if sibNode and sibNode.nodeName == 'failure':
        print testCase.getAttribute("name"), " --> ","FAIL"
    else:
        print testCase.getAttribute("name"), " --> ","PASS"