使用xml

时间:2019-01-31 20:37:51

标签: python xml elementtree

我有以下xml(简化版):

基础:

<root>
    <child1></child1>
    <child2></child2>
</root>

ChildInfo:

<ChildInfo>
    <Name>Something</Name>
    <School>ElementarySchool</School>
    <Age>7</Age>
</ChildInfo>

ExpectedOutput:

<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文件并将其作为可以整体添加的元素?还是应该只更改库?

1 个答案:

答案 0 :(得分:1)

使用bytes时,可以直接将JmeterSampler.xml作为Element加载,然后只需将Element附加到所需的位置即可:

ET.fromstring(...)

打印:

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'))