• 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()

  • 相关阅读:
    Pyechart——学习
    matplotlib——散点图、条形图、直方图
    matplotlib——折线图
    寻找n以内的亲密数对
    Golang判断时间点处于今天
    寒假作业3
    寒假作业2
    面向对象程序设计寒假作业1
    自我介绍
    关于cve2019_0708的反弹shell
  • 原文地址:https://www.cnblogs.com/moss_tan_jun/p/12636899.html
Copyright © 2020-2023  润新知