我在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的内容;这些如下所示。
(first.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的代码,但代码只是转储main.xml文件底部的first.xml和second.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>
非常感谢任何帮助。谢谢,MikG
答案 0 :(得分:2)
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>