使用Python向XML添加容器元素

2024-09-27 07:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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文件(虚拟.xml)地址:

<book>
    <title> Everyday Italian </title>
    <author> Giada DeLaurentiis </author>
    <language> English </language>
    <section> Cooking </section>
</book>

以下是我希望新XML(文件名)的外观:

<book>
    <title> Everyday Italian </title>
    <author> Giada DeLaurentiis </author>
    <languages>
    <language> English </language>
    </languages>
    <section> Cooking </section>
</book>

请帮忙。我似乎无法将容器元素“languages”正确地添加到新的XML文件中。你知道吗

谢谢


Tags: fromimporttitlesectionrootxmllanguagedom
1条回答
网友
1楼 · 发布于 2024-09-27 07:25:56
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插入到根。你知道吗

相关问题 更多 >

    热门问题