zoukankan      html  css  js  c++  java
  • python xml mode(2)

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

  • 相关阅读:
    解决电脑故障通用三部曲
    为什么有的人留邮箱的时候会把@写成#
    试用DreamWeaver CS6
    在CSDN上提问
    视频网站保存观看记录相关
    QQ浏览器设置无效后重新设置
    FastCopy总结
    如何在PC上多开微信
    Messager不能撤回消息
    用CSS3动画 animation实现图片旋转
  • 原文地址:https://www.cnblogs.com/moss_tan_jun/p/12636899.html
Copyright © 2011-2022 走看看