Skip to main content
 首页 » 编程设计

python之使用 Python 将 XML 合并到父 XML 文件中

2024年10月17日798°冷暖

我发现了几个在 SO 上使用 Python 合并 XML 的示例,但是我希望将两个测试用例 XML 合并到父 XML 中。

这是我的父 XML (main.xml)

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE propertiesconfiguration_my_campaign> 
<exconfig> 
  <manager master_node="themaster"> 
    <testspecif class="MySpec" name="MY_TEST"> 
      <report> 
        *** Report Attributes in here *** 
      </report> 
        *** Looking to post Test Cases in here *** 
    </testspecif> 
  </manager> 
</exconfig> 

我在上面的 XML 中突出显示了我希望发布以下测试用例 XML 的位置;这些如下所示。

(第一个.xml)

  <testcase class="CTestCase000001a" name="TC-000001a"> 
    *** Test case Attributes in here *** 
  </testcase> 

(second.xml)

  <testcase class="CTestCase000001b" name="TC-000001b"> 
    *** Test case Attributes in here *** 
  </testcase> 

这是我用来合并 XML 的代码,但是代码只是将 first.xml 和 second.xml 文本转储到 main.xml 文件的底部。

from xml.etree import ElementTree as et 
 
def combine(files): 
    first = None 
    for filename in files: 
        data = et.parse(filename).getroot() 
        if first is None: 
            first = data 
        else: 
            first.extend(data) 
    if first is not None: 
        f = open('C:/temp/newXML.xml', 'wb') 
        f.write(et.tostring(first)) 
        f.close() 
        # return et.tostring(first) 
 
combine(('C:/main.xml','C:/first.xml','C:/second.xml')) 

我希望输出的是这样的,所有测试用例 XML 文本都嵌入在 testspecif 元素内的报告节点中:

<!DOCTYPE propertiesconfiguration_my_campaign> 
<exconfig> 
  <manager master_node="themaster"> 
    <testspecif class="MySpec" name="MY_TEST"> 
      <report> 
        *** Report Attributes in here *** 
      </report> 
      <testcase class="CTestCase000001a" name="TC-000001a"> 
        *** Test case Attributes in here *** 
      </testcase>   
      <testcase class="CTestCase000001b" name="TC-000001b"> 
        *** Test case Attributes in here *** 
      </testcase>        
    </testspecif> 
  </manager> 
</exconfig> 

如有任何帮助,我们将不胜感激。谢谢,米克格

请您参考如下方法:

from xml.etree import ElementTree as et 
 
 
c1, c2 = et.parse("c1.xml"), et.parse("c2.xml") 
 
par_xml = et.parse("par.xml") 
 
test = par_xml.find(".//testspecif") 
 
test.extend([c1.find(".//testcase"), c2.find(".//testcase")]) 
 
print(et.tostring(par_xml.getroot())) 
# par.write("par.xml",encoding="utf-8", xml_declaration=True) 

您的示例输入会给您:

<exconfig> 
  <manager master_node="themaster"> 
    <testspecif class="MySpec" name="MY_TEST"> 
      <report> 
 
      </report> 
 
    <testcase class="CTestCase000001a" name="TC-000001a"> 
    *** Test case Attributes in here *** 
</testcase> 
   <testcase class="CTestCase000001b" name="TC-000001b"> 
    *** Test case Attributes in here *** 
  </testcase> 
</testspecif> 
  </manager> 
</exconfig>