博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python xml mod(1)

Posted on 2020-04-05 13:24  moss_tan_jun  阅读(170)  评论(0编辑  收藏  举报
# -*- coding: utf-8 -*-

from xml.dom.minidom import parse


def writexml():
dom = parse("server.xml")
root = dom.documentElement
systemlist = root.getElementsByTagName("system")
system_node = systemlist[0]

bindIp_node = dom.createElement("property")
bindIp_node.setAttribute("name","bindIp")
bindIp_node.setAttribute("name2", "mytest")
bindIp_text_value = dom.createTextNode("192.168.1.134")
bindIp_node.appendChild(bindIp_text_value)

system_node.appendChild(bindIp_node)

with open("server.xml","w") as f:
dom.writexml(f, addindent=' ', encoding='utf-8')

def updateXML():
domTree = parse("server.xml")
rootNode = domTree.documentElement
names = rootNode.getElementsByTagName("property")
for name in names:
if name.childNodes[0].data == "192.168.1.139":
name.childNodes[0].data = "1234"

with open('server.xml', 'w') as f:
domTree.writexml(f, addindent=' ', encoding='utf-8')


def cheknode():
domTree = parse("server.xml")
rootNode = domTree.documentElement
system_list = rootNode.getElementsByTagName("property")

for prs in system_list:
#print(prs.hasAttribute('name'))
#print(prs.getAttribute('name'))
if prs.getAttribute('name') == "managerIp":
print("managerIP:%s" %prs.childNodes[0].data)



if __name__ == '__main__':
#writexml()
#updateXML
cheknode()