使用 xml 添加完整 xml 作为 python 中 xml 节点的子节点
Add complete xml as a child of an xml node in python using xml
我有以下 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 文件是我唯一能做到的方法。
到目前为止我有以下内容
pythonfile.py:
import xml.etree.ElementTree as ET
finalScript=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 文件并将其作为一个元素保存,可以作为一个整体添加?还是我应该只更改库?
在使用ET.fromstring(...)
时可以直接加载JmeterSampler.xml
作为Element,然后只需要将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>
我有以下 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 文件是我唯一能做到的方法。
到目前为止我有以下内容
pythonfile.py:
import xml.etree.ElementTree as ET
finalScript=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 文件并将其作为一个元素保存,可以作为一个整体添加?还是我应该只更改库?
在使用ET.fromstring(...)
时可以直接加载JmeterSampler.xml
作为Element,然后只需要将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>