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

python xml mode(2)

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

from xml.dom.minidom import parse

def readXML():
domTree = parse("./defalt.xml")
rootNode = domTree.documentElement
print(rootNode.nodeName)


customers = rootNode.getElementsByTagName("customer")
print("****所有顾客信息****")
for customer in customers:
if customer.hasAttribute("ID"):
print("ID:", customer.getAttribute("ID"))
name = customer.getElementsByTagName("name")[0]
print(name.nodeName, ":", name.childNodes[0].data)
phone = customer.getElementsByTagName("phone")[0]
print(phone.nodeName, ":", phone.childNodes[0].data)
comments = customer.getElementsByTagName("comments")[0]
print(comments.nodeName, ":", comments.childNodes[0].data)


def writeXML():
domTree = parse("./defalt.xml")
rootNode = domTree.documentElement
customer_node = domTree.createElement("customer")
customer_node.setAttribute("ID", "C003")

name_node = domTree.createElement("name")
name_text_value = domTree.createTextNode("kavin")
name_node.appendChild(name_text_value)
customer_node.appendChild(name_node)

phone_node = domTree.createElement("phone")
phone_text_value = domTree.createTextNode("32467")
phone_node.appendChild(phone_text_value)
customer_node.appendChild(phone_node)

comments_node = domTree.createElement("comments")
cdata_text_value = domTree.createCDATASection("A small but healthy company.")
comments_node.appendChild(cdata_text_value)
customer_node.appendChild(comments_node)

rootNode.appendChild(customer_node)

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



def updateXML():
domTree = parse("./defalt.xml")
rootNode = domTree.documentElement
names = rootNode.getElementsByTagName("name")
for name in names:
if name.childNodes[0].data == "Acme Inc.":
pn = name.parentNode
phone = pn.getElementsByTagName("phone")[0]
phone.childNodes[0].data = 99999

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

if __name__ == '__main__':
updateXML()
#writeXML()