zoukankan      html  css  js  c++  java
  • python自带的minidom创建和解析xml

    #-------------------------------------------------------------------------------
    # Name:        模块1
    # Purpose:     本文通过xml.dom.minidom创建一个xml文档,然后再解析出来,用以熟悉相关接口方法的使用。
    #
    # Author:      User
    #
    # Created:     31/08/2012
    # Copyright:   (c) User 2012
    # Licence:     <your licence>
    #-------------------------------------------------------------------------------
    from xml.dom import minidom, Node
    
    class BooksXmlGenerator:
        def __init__(self):
            self.__doc =minidom.Document()
            self.__doc.appendChild(self.__doc.createComment("This is a sample xml")) #生产:<!--简单的xml-->
            self.__books = self.__doc.createElement("books")
            self.__doc.appendChild(books)
            self.__booksSource =[]
    
        def SetBooksSource(self, booksSource):
            for source in booksSource:
                self.__booksSource.append(source)
    
    
        def GenerateBooksXml(self):
            for newBook in self.__booksSource:
                book = self.__doc.createElement("book")
                book.setAttribute("id", newBook["id"])
    
                title = self.__doc.createElement("title")
                title.appendChild(self.__doc.createTextNode(newBook["title"]))
                book.appendChild(title)
    
                author = self.__doc.createElement("author")
                name = self.__doc.createElement("name")
    
                firstName = self.__doc.createElement("firstname")
                firstName.appendChild(self.__doc.createTextNode(newBook["firstname"]))
    
                lastName = self.__doc.createElement("lastname")
                lastName.appendChild(self.__doc.createTextNode(newBook["lastname"]))
    
                name.appendChild(firstName)
                name.appendChild(lastName)
                author.appendChild(name)
                book.appendChild(author)
    
                pubdate = self.__doc.createElement("pubdate")
                pubdate.appendChild(self.__doc.createTextNode(newBook["pubdate"]))
                book.appendChild(pubdate)
    
                self.__books.appendChild(book)
    
        def WriteToFile(self, path):
            f = file(path,"w")
            self.__doc.writexml(f)
            f.close()
    
    class BooksXmlScanner:
        def __init__(self, path):
            self.__doc = minidom.parse(path)
            for child in self.__doc.childNodes:
                if child.nodeType ==Node.COMMENT_NODE:
                    print "Conment : " , child.nodeValue
                if child.nodeType == Node.ELEMENT_NODE:
                    self.__HandleBooks(child)
    
        def __HandleBooks(self, node):
            for child in node.childNodes:
                if child.nodeType == Node.ELEMENT_NODE and child.tagName =="book":
                    bookid = child.getAttribute("id")
                    print "*"*20
                    print "Book id : " , bookid
                    self.__HandleBook(child)
    
        def __HandleBook(self, node):
            for child in node.childNodes:
                if child.nodeType ==Node.ELEMENT_NODE:
                    if child.tagName == "title":
                        print "Title : " , self.__GetText(child.firstChild)
                    if child.tagName == "author":
                        self.__HandleAuthor(child)
                    if child.tagName == "pubdate":
                        print "Pubdate : " , self.__GetText(child.firstChild)
    
        def __GetText(self, node):
            if node.nodeType ==Node.TEXT_NODE:
                return node.nodeValue
            else:
                return ""
    
        def __HandleAuthor(self,node):
            author = node.firstChild
            for child in author.childNodes:
                if child.nodeType == Node.ELEMENT_NODE:
                    if child.tagName == "firstname" :
                        print "Firstname : ", self.__GetText(child.firstChild)
                    if child.tagName == "lastname" :
                        print "Lastname : " , self.__GetText(child.firstChild)
    
    def main():
        path ="D:\\books.xml"
        booksGenerator = BooksXmlGenerator()
        sourceList =[{"id":"1002","title":"Love","firstname":"Mike","lastname":"Li","pubdate":"2012-1-10"},{"id":"1004","title":"Harry Potter","firstname":"Peter","lastname":"Chen","pubdate":"2012-11-11"},{"id":"1003","title":"Steve.Jobs","firstname":"Tom","lastname":"Wang","pubdate":"2012-1-19"}]
        booksGenerator.SetBooksSource(sourceList)
        booksGenerator.GenerateBooksXml()
        booksGenerator.WriteToFile(path)
        print "Write to file completely."
    
        booksXmlScanner = BooksXmlScanner(path)
    
    if __name__ == '__main__':
        main()
    
    #generated xml
    #<?xml version="1.0" ?>
    #<!--This is a simple xml.-->
    #<books>
    #   <book id="1001">
    #     <title>
    #     An apple
    #     </title>
    #   <author>
    #     <name>
    #       <firstname>
    #       Peter
    #       </firstname>
    #       <lastname>
    #       Zhang
    #       </lastname>
    #     </name>
    #   </author>
    #   <pubdate>
    #   2012-1-12
    #   </pubdate>
    #   </book>
    #
    # .................
    #</books>
  • 相关阅读:
    C# 操作Orcle数据库
    WinDbg排查CPU高的问题
    NetCore微服务实战体系:日志管理
    NetCore微服务实战体系:Grpc+Consul 服务发现
    解惑求助-关于NetCore2.2中间件响应的问题
    EF Join连接查询的坑
    给DataTable添加行的几种方式
    [C#] 折腾海康威视的人体测温 模组
    [WPF 学习] 15.播放百度合成的语音
    [WPF 学习] 14.PlaceHolder的简单实现
  • 原文地址:https://www.cnblogs.com/ankier/p/2665319.html
Copyright © 2011-2022 走看看