如何使用minidom python插入子元素并写入xml文件?

时间:2018-07-04 09:33:18

标签: python xml python-2.7 xml-parsing

我有带有xml值的config.xml文件和一个python脚本,我正试图通过它使用dom库添加新属性。请建议如何使用minidom添加/插入新属性,以及如何将其写回到原始config.xml,以免xml无效。 以下是我的代码: config.xml:-

<?xml version="1.0" encoding="UTF-8"?>
<Targets version="0.0">
<Target TYPE="pyjava.python.com" NAME="pyjava">
    <Attribute NAME="maxslot" VALUE="8"></Attribute>
    <Attribute NAME="accessLevel" VALUE="remoteLoginEnabled"></Attribute>
    <Attribute NAME="name" VALUE="PyJava"></Attribute>
    <Attribute NAME="id" VALUE="9876"></Attribute>
    <Attribute NAME="make" VALUE="TOTO"></Attribute>
    <Attribute NAME="max" VALUE="12"></Attribute>
    <Attribute NAME="min" VALUE="8"></Attribute>
</Target>

我要添加的属性是:-

<Attribute NAME="ABCD" VALUE="8111"></Attribute>

直到现在我编写的代码是:-

from xml.dom import minidom
import xml.dom
#parsing the xml
dom = minidom.parse('./mac_config.xml')
root = dom.firstChild
#print(root)
#print(dom.getElementsByTagName('Attribute'))
newelement = dom.createElement("Attribute")
newelement.attributes['NAME'] = "snmp"
newelement.attributes['VALUE'] = "1234"
newtext = dom.createTextNode('')
newelement.appendChild(newtext)
items = dom.getElementsByTagName("Target")
item= items[0]
item_child = item.childNodes
item.insertBefore(newelement,item_child[6])
#item.appendChild(newelement)
item.normalize()
print(dom.toxml())

如何编写和对齐输出? 请让我知道如何解决此问题并将其写回到config.xml,因为它没有提供正确的输出。 PS:使用Element Tree时出现问题,因为python版本是2.6。

0 个答案:

没有答案