【问题标题】:Minidom element insertion into xmlMinidom 元素插入到 xml
【发布时间】:2015-04-18 21:12:25
【问题描述】:

我在向 xml 文档中插入数据结构时遇到了一些问题。但是没有大的成功。我有文件例如。

<?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()

【问题讨论】:

  • 效果如何? document = parse('mini.xml') 行对我产生解析错误:xml.parsers.expat.ExpatError: no element found: line 14, column 0
  • 对不起,我的错。源 xml 格式错误。问题现已修复。
  • 如果有帮助:使用此代码element = document.createElement("mObject") element.appendChild(document.createTextNode("Hello")) document.childNodes[0].childNodes[1].appendChild(element) 我得到&lt;mObject&gt;Hello&lt;/mObject&gt; 作为&lt;mcdata&gt; 的孩子

标签: python xml minidom


【解决方案1】:

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

#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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多