2017-07-26 20 views
0

PythonでXMLパーサーを作成して、どのテストケースが失敗しているかを確認し、失敗した場合はエラーメッセージを確認します。私は他のタグと一緒に失敗しているテストケースのその部分だけを抽出したいと思います。 美しいスープを使ってみました。正しく成功することができませんでした。以下は私のXMLファイルのサンプルです:PythonがPythonのタグの前後にタグを取得する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

あなたは使用 XMLパーサ、ない書き込みものにしたいです。で

'Invalid credentials: Check the login credentials' 

:次に

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) 

この出力

はまた少し楽をするために<tests>...</tests>タグで全体のXMLをラップすることもできますファイルから読み込むには、xml_node = ET.fromstring(string)を次のように置き換えます。

with open('file/path') as f: 
    xml_node = ET.fromstring(f.read()) 
+0

これを文字列の一部として追加するときに機能します。あなたはファイルから読むために私を助けてもらえますか? – Yadunandana

+0

@ Yadunandana私の更新された回答を参照してください – DeepSpace

+0

'string'変数の名前を変更したいかもしれません。 – CristiFati

関連する問題