我想在Python中编写一个XML解析器,用于检查哪些测试用例失败,如果失败,请检查错误消息。我想只提取与其他标签一起失败的测试用例部分。 我尝试过使用美味汤。无法正常成功。以下是我的XML文件示例:
<test>
<test_str>Test Case #1: Check for login</test_str>
<testcase>
<pass_status>false</pass_status>
<criticality>true</criticality>
<errorMsg>Invalid credentials:
Check the login credentials </errorMsg>
<tags>
<string>test01</string>
</tags>
<parent reference="../../../.."/>
<failedSince>0</failedSince>
</testcase>
</test>
<test>
<test_str>Test Case 02:Pass valid credentials
by selecting valid username</test_str>
<testcase>
<pass_status>true</pass_status>
<criticality>true</criticality>
<tags>
<string>test01</string>
</tags>
<parent reference="../../../.."/>
<failedSince>0</failedSince>
</testcase>
</test>
答案 0 :(得分:0)
您希望使用 XML解析器,而不是编写。
您可能还希望使用<tests>...</tests>
标记包装整个XML,以使生活更轻松:
string = '''<tests>
<test>
<test_str>Test Case #1: Check for login</test_str>
<testcase>
<pass_status>false</pass_status>
<criticality>true</criticality>
<errorMsg>Invalid credentials: Check the login credentials </errorMsg>
<tags>
<string>test01</string>
</tags>
<parent reference="../../../.."/>
<failedSince>0</failedSince>
</testcase>
</test>
<test>
<test_str>Test Case 02:Pass valid credentials by selecting valid username</test_str>
<testcase>
<pass_status>true</pass_status>
<criticality>true</criticality>
<tags>
<string>test01</string>
</tags>
<parent reference="../../../.."/>
<failedSince>0</failedSince>
</testcase>
</test>
</tests>'''
然后:
import xml.etree.ElementTree as ET
xml_node = ET.fromstring(string)
for test_node in xml_node.findall('test'):
test_case_node = test_node.find('testcase')
pass_status_node = test_case_node.find('pass_status')
if pass_status_node.text == 'false':
print(test_case_node.find('errorMsg').text)
输出:
'Invalid credentials: Check the login credentials'
要从文件中读取,只需将xml_node = ET.fromstring(string)
替换为:
with open('file/path') as f:
xml_node = ET.fromstring(f.read())