我有以下 xmls(简化):根据:<root> <child1></child1> <child2></child2></root>儿童信息:<ChildInfo> <Name>Something</Name> <School>ElementarySchool</School> <Age>7</Age></ChildInfo>预期输出:<root> <child1></child1> <child2> <ChildInfo> <Name>Something</Name> <School>ElementarySchool</School> <Age>7</Age> </ChildInfo> </child2></root>这种情况被简化只是为了提供我需要的功能。真实案例场景中的 XMls 非常大,因此逐行创建子元素不是一种选择,因此解析 xml 文件是我能做到的唯一方法。到目前为止,我有以下内容蟒蛇文件.py:import xml.etree.ElementTree as ETfinalScript=ET.parse(r"resources/JmeterBase.xml")samplerChild=ET.parse(r"resources/JmeterSampler.xml")root=finalScript.getroot()samplerChildRoot=ET.Element(samplerChild.getroot())root.append(samplerChildRoot)但这并没有提供所需的选项,并且在所有 xml 指南中,示例都非常简单并且不处理这种情况。有没有办法加载一个完整的xml文件并将其作为一个可以作为一个整体添加的元素?还是我应该改变图书馆?
1 回答

蝴蝶不菲
TA贡献1810条经验 获得超4个赞
JmeterSampler.xml使用时可以直接加载为 Element ET.fromstring(...),然后只需要将 Element 附加到您想要的位置:
import xml.etree.ElementTree as ET
finalScript = ET.parse(r"resources/JmeterBase.xml")
samplerChild = ET.fromstring(open(r"resources/JmeterSampler.xml").read())
root = finalScript.getroot()
child2 = root.find('child2')
child2.append(samplerChild)
print (ET.tostring(root, 'utf-8'))
印刷:
<root>
<child1 />
<child2><ChildInfo>
<Name>Something</Name>
<School>ElementarySchool</School>
<Age>7</Age>
</ChildInfo>
</child2>
</root>
添加回答
举报
0/150
提交
取消