Minidom 元素插入 xml

Minidom element insertion into xml

我在将数据结构插入 xml document.But 时遇到了一些问题,没有大 success.I 文件,例如

<?xml version="1.0" ?>
<marl version="2.1" xmlns="xxxx.xsd">
    <mcdata id="2" scope="all" type="plan">
        <header>
            <log action="created"/>
        </header>
        <mObject class="foo" distName="a-1">
            <p name="Ethernet">false</p>
            <list name="pass"/>
        </mObject>
        <mObject class="bar" distName="a-1/b-2">
            <p name="Voltage">false</p>
        </mObject>
    </mcdata>
</marl>

我的代码的基本版本是这样的,但似乎没有效果,因为 output.xml 与 mini.xml 相同。

from xml.dom.minidom import *
document = parse('mini.xml')
mo = document.getElementsByTagName("mObject")
element = document.createElement("mObject")
mo.append(element)
with open('output.xml', 'wb') as out:
    document.writexml(out)
    out.close()

创建一个新节点并根据需要对其进行装饰:

#create node <mObject>
element = document.createElement("mObject")
#add text content to the node
element.appendChild(document.createTextNode("content"))
#add attribute id to the node
element.setAttribute("id"  , "foo")
#result: <mObject id="foo">content</mObject>

将新创建的节点添加到父节点:

#select a parent node
mc = document.getElementsByTagName("mcdata")[0]
#append the new node as child of the parent
mc.appendChild(element)