工作中同事涉及到用python修改xml文件,网上看了下相关的文章和例子,方法其实挺多的,用了比较简单的方法实现在指定节点中插入和删除相关元素和属性,代码如下:
# -*- coding:UTF-8 -*-
import xml.etree.ElementTree as ET
def add_node():
x = 0
for i in devE:
if i.tag != "serial":
x += 1
continue
else:
break
ifE = ET.Element('interface')
ifE.set('type', 'bridge')
macE = ET.SubElement(ifE, 'mac')
macE.set("address", "54:52:00:22:93:88")
brE = ET.SubElement(ifE, 'source')
brE.set("bridge", "br1")
devE.insert(x, ifE)
def del_node():
for i in devE.findall("interface"):
if i.find("mac").get("address") == "54:52:00:22:93:88":
del devE[devE.getchildren().index(i)]
if __name__ == "__main__":
tree = ET.parse("test1.xml")
root = tree.getroot()
devE = root.find('devices')
add_node()
#del_node()
tree.write('test1.xml')
|
阅读(7336) | 评论(0) | 转发(0) |