使用xml.etree.ElementTree获取CDATA

时间:2015-06-16 11:01:50

标签: python xml xml-parsing

我有以下xml:

<?xml version="1.0" ?>
<testsuite errors="1" failures="0" name="test" tests="1" time="3.393">
        <testcase classname="test" name="case time="3.393">
                <error message="'test' object has no attribute 'test'" type="AttributeError">
<![CDATA["HERES THE DETAILED ERROR"]]>             </error>
        </testcase>
        <system-out>
<![CDATA["ANOTHER TEXT"]]>
 </system-out>
        <system-err>
<![CDATA[]]>    </system-err>
</testsuite>

我有以下解析代码:

tree = ET.parse("test-reports/{0}".format(resultfile))
test = tree.getroot()
for child in test:
    if child.tag == "testcase":
        if child.find("error") is not None:
            state = 2
            # How do I get <error>s CDATA here?
        else:
            state = 1

如何在标签内获取CDATA文本(第一个CDATA)

1 个答案:

答案 0 :(得分:2)

你可以做 -

ertag = child.find("error")
cdatatext = ertag.text
print(cdatatext)

这会打印 -

"HERES THE DETAILED ERROR"