如何使用Python复制xml元素?

gab*_*esz 5 python xml

我有一个看起来像这样的XML文件:

 <a>
   <b>
    <c>World</c>
   </b>
 </a>
Run Code Online (Sandbox Code Playgroud)

并应如下所示:

 <a>
  <b>
   <c>World</c>
   <c>World</c>
  </b>
 </a> 
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

import xml.etree.ElementTree as ET

file=open("6x6.xml", "r")
site=file.ET.Element("b")
for c in file:
  site.append(c)
file.write("out.xml")
file.close()
Run Code Online (Sandbox Code Playgroud)

har*_*r07 7

您可以copy.deepcopy()用来实现这一目标,例如:

import xml.etree.ElementTree as ET
import copy

s = """<a>
   <b>
    <c>World</c>
   </b>
 </a>"""

file = ET.fromstring(s)
b = file.find("b")
for c in file.findall(".//c"):
    dupe = copy.deepcopy(c) #copy <c> node
    b.append(dupe) #insert the new node

print(ET.tostring(file))
Run Code Online (Sandbox Code Playgroud)

输出:

<a>
   <b>
    <c>World</c>
   <c>World</c>
   </b>
 </a>
Run Code Online (Sandbox Code Playgroud)

相关问题:etree克隆节点