猿问

使用xml在python中添加完整的xml作为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 文件是我能做到的唯一方法。


到目前为止,我有以下内容


蟒蛇文件.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文件并将其作为一个可以作为一个整体添加的元素?还是我应该改变图书馆?


白猪掌柜的
浏览 569回答 1
1回答

蝴蝶不菲

JmeterSampler.xml使用时可以直接加载为 Element ET.fromstring(...),然后只需要将 Element 附加到您想要的位置:import xml.etree.ElementTree as ETfinalScript = 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>&nbsp; &nbsp; <child1 />&nbsp; &nbsp; <child2><ChildInfo>&nbsp; &nbsp; <Name>Something</Name>&nbsp; &nbsp; <School>ElementarySchool</School>&nbsp; &nbsp; <Age>7</Age>&nbsp; &nbsp; </ChildInfo>&nbsp; &nbsp; </child2></root>
随时随地看视频慕课网APP

相关分类

Python
我要回答