如何在 Python 中深度复制 xml 子元素

我对 XML 和 Python 非常陌生,我将本网站和其他网站上的帖子中的内容放在一起。我正在尝试使用 ElementTree 深度复制一个元素并附加到另一个元素。从下面的输入表开始:


<Company>

    <Identifier>Benesolv</Identifier>

    <Employee>

        <EESSN>111111111</EESSN>

        <Dependent>

            <SSN>222222222</SSN>

        </Dependent>

    </Employee>

</Company>

这是我拥有的有效代码,但不是我最终想要的。


import xml.etree.ElementTree as ET

import copy


tree = ET.parse("file.xml")

root = tree.getroot()


x = copy.deepcopy(root[0])

for elem in tree.findall("Company/Employee/Dependent"):

    elem.append(copy.deepcopy(x))


tree.write("file.xml")

这是复制<Identifier>元素并附加到<Dependent>元素的输出:


<Company>

    <Identifier>Benesolv</Identifier>

    <Employee>

        <EESSN>111111111</EESSN>

        <Dependent>

            <SSN>222222222</SSN>

        <Identifier>Benesolv</Identifier>

    </Dependent>

    </Employee>

</Company>

我想要做的是复制 <EESSN> 元素并附加到<Dependent>元素,但我不知道如何。我想我只是用root[0]可以识别<EESSN>元素的东西替换了,但是我尝试过的一切都不起作用。谢谢您的帮助。


期望的输出:


<Company>

    <Identifier>Benesolv</Identifier>

    <Employee>

        <EESSN>111111111</EESSN>

        <Dependent>

            <SSN>222222222</SSN>

        <EESSN>111111111</EESSN>

        </Dependent>

    </Employee>

</Company>


森栏
浏览 237回答 1
1回答

一只甜甜圈

你不需要深度复制任何东西;只需将EESSN元素分配给一个变量并将其附加到Dependent.XML 输入<Company>&nbsp; &nbsp; <Identifier>Benesolv</Identifier>&nbsp; &nbsp; <Employee>&nbsp; &nbsp; &nbsp; &nbsp; <EESSN>111111111</EESSN>&nbsp; &nbsp; &nbsp; &nbsp; <Dependent>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <SSN>222222222</SSN>&nbsp; &nbsp; &nbsp; &nbsp; </Dependent>&nbsp; &nbsp; </Employee></Company>Python代码import xml.etree.ElementTree as ETtree = ET.parse("input.xml")for employee in tree.findall("Employee"):&nbsp; &nbsp; eessn = employee.find("EESSN")&nbsp; &nbsp; for dependent in employee.findall("Dependent"):&nbsp; &nbsp; &nbsp; &nbsp; dependent.append(eessn)tree.write("output.xml")XML 输出<Company>&nbsp; &nbsp; <Identifier>Benesolv</Identifier>&nbsp; &nbsp; <Employee>&nbsp; &nbsp; &nbsp; &nbsp; <EESSN>111111111</EESSN>&nbsp; &nbsp; &nbsp; &nbsp; <Dependent>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <SSN>222222222</SSN>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <EESSN>111111111</EESSN>&nbsp; &nbsp; &nbsp; &nbsp; </Dependent>&nbsp; &nbsp; </Employee></Company>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python