这是我的代码:
from xml.dom import minidom
from xml.dom.minidom import parse
import xml.etree.ElementTree as ET
xml_file = "dummy.xml"
xmlFile = ET.parse(xml_file)
root = xmlFile.getroot()
root.keys()
newroot = ET.Element("languages")
for child in root:
if child.tag == "language":
newroot.insert(1, newroot)
xmlFile.write("fileName")
else:
print "no"
这是原始的XML文件(dummy.xml):
<book>
<title> Everyday Italian </title>
<author> Giada DeLaurentiis </author>
<language> English </language>
<section> Cooking </section>
</book>
以下是我希望新XML(fileName)的样子:
<book>
<title> Everyday Italian </title>
<author> Giada DeLaurentiis </author>
<languages>
<language> English </language>
</languages>
<section> Cooking </section>
</book>
请帮忙。我似乎无法添加容器元素&#34;语言&#34;正确地到新的XML文件。
由于
答案 0 :(得分:0)
from xml.dom import minidom
from xml.dom.minidom import parse
import xml.etree.ElementTree as ET
xml_file = "dummy.xml"
xmlFile = ET.parse(xml_file)
root = xmlFile.getroot()
root.keys()
newroot = ET.Element("languages")
for child in root:
if child.tag == "language":
newroot.insert(1, child)
root.remove(child)
root.insert(1, newroot)
xmlFile.write("newdummy.xml")
else:
print "no"
您需要先将您的孩子插入newroot,然后将newroot插入根目录。