用python解析xml文件

作者: 此生望尽天涯路 | 来源:发表于2018-06-16 20:25 被阅读0次

    关于xml文件,python可以用两种方式来进行解析,DOM(Document object model)和SAX(simple API for xml)。其中DOM是将xml数据加载到内存中形成一个树,通过对树的操作来操作xml,之后可以通过DOM提供的函数对文档进行读取和修改。SAX是基于事件驱动的API,包括两个部分:解析器和事件处理器。首先对xml数据进行解析,过程中会触发事件:开始事件start_element、 结束事件end_element 、数据char_data 。然后事件处理器会进行处理。
    如:当SAX在解析一个节点时<li><a href="/python">Python</a></li> 会产生三个事件:
    2.1 start_element事件,分别读取<li>、<a href="/python">
    2.2 end_element事件,分别读取</a>、</li>
    2.3 char_data事件、读取Python
    下面要用到的xml文件:

    <collection shelf="New Arrivals">
    <movie title="Enemy Behind">
       <type>War, Thriller</type>
       <format>DVD</format>
       <year>2003</year>
       <rating>PG</rating>
       <stars>10</stars>
       <description>Talk about a US-Japan war</description>
    </movie>
    <movie title="Transformers">
       <type>Anime, Science Fiction</type>
       <format>DVD</format>
       <year>1989</year>
       <rating>R</rating>
       <stars>8</stars>
       <description>A schientific fiction</description>
    </movie>
       <movie title="Trigun">
       <type>Anime, Action</type>
       <format>DVD</format>
       <episodes>4</episodes>
       <rating>PG</rating>
       <stars>10</stars>
       <description>Vash the Stampede!</description>
    </movie>
    <movie title="Ishtar">
       <type>Comedy</type>
       <format>VHS</format>
       <rating>PG</rating>
       <stars>2</stars>
       <description>Viewable boredom</description>
    </movie>
    </collection>
    

    使用Dom解析xml文件:

    from xml.dom.minidom import parse
    import xml.dom.minidom
    
    # 使用minidom解析器打开 XML 文档
    DOMTree = xml.dom.minidom.parse("movies.xml")
    collection = DOMTree.documentElement
    if collection.hasAttribute("shelf"):
       print ("Root element : %s" % collection.getAttribute("shelf"))
    
    # 在集合中获取所有电影
    movies = collection.getElementsByTagName("movie")
    
    # 打印每部电影的详细信息
    for movie in movies:
       print ("*****Movie*****")
       if movie.hasAttribute("title"):
          print ("Title: %s" % movie.getAttribute("title"))
    
       type = movie.getElementsByTagName('type')[0]
       print ("Type: %s" % type.childNodes[0].data)
       format = movie.getElementsByTagName('format')[0]
       print ("Format: %s" % format.childNodes[0].data)
       rating = movie.getElementsByTagName('rating')[0]
       print ("Rating: %s" % rating.childNodes[0].data)
       description = movie.getElementsByTagName('description')[0]
       print ("Description: %s" % description.childNodes[0].data)
    

    结果如下:

    Root element : New Arrivals
    *****Movie*****
    Title: Enemy Behind
    Type: War, Thriller
    Format: DVD
    Rating: PG
    Description: Talk about a US-Japan war
    *****Movie*****
    Title: Transformers
    Type: Anime, Science Fiction
    Format: DVD
    Rating: R
    Description: A schientific fiction
    *****Movie*****
    Title: Trigun
    Type: Anime, Action
    Format: DVD
    Rating: PG
    Description: Vash the Stampede!
    *****Movie*****
    Title: Ishtar
    Type: Comedy
    Format: VHS
    Rating: PG
    Description: Viewable boredom
    

    Dom解析xml为树结构:

    Dom解析xml为树
    参考教程:菜鸟教程Dom解析xml
    SAX解析xml:
    import xml.parsers.expat
    
    class ExParser(object):
        '''Parse roster xml'''
        def __init__(self, xml_raw):
            '''init parser and setup handlers'''
            self.parser = xml.parsers.expat.ParserCreate()
    
            #connect handlers
            self.parser.StartElementHandler = self.start_element
            self.parser.EndElementHandler = self.end_element
            self.parser.CharacterDataHandler = self.char_data
            self.parser.Parse(xml_raw)
            del(xml_raw)
    
        def start_element(self, name, attrs):
            '''Start xml element handler'''
            print ('start:'+name)
    
        def end_element(self, name):
            '''End xml element handler'''
            print ('end:'+name)
    
        def char_data(self, data):
            '''Char xml element handler'''
            print ('data is '+data)
    
    f = open("movies.xml")
    data = f.read()
    parser = ExParser(data)
    
    

    结果如下:(部分展示)

    start:collection
    data is 
    
    start:movie
    data is 
    
    data is    
    start:type
    data is War, Thriller
    end:type
    data is 
    
    data is    
    start:format
    data is DVD
    end:format
    data is 
    
    data is    
    start:year
    data is 2003
    end:year
    data is 
    
    data is    
    start:rating
    data is PG
    end:rating
    data is 
    
    data is    
    start:stars
    data is 10
    end:stars
    data is 
    
    data is    
    start:description
    data is Talk about a US-Japan war
    end:description
    data is 
    
    end:movie
    data is 
    
    start:movie
    data is 
    
    data is    
    start:type
    data is Anime, Science Fiction
    end:type
    data is 
    
    data is    
    start:format
    data is DVD
    end:format
    data is 
    
    data is    
    start:year
    data is 1989
    end:year
    data is 
    
    data is    
    start:rating
    data is R
    end:rating
    data is 
    
    data is    
    start:stars
    data is 8
    end:stars
    data is 
    
    data is    
    start:description
    data is A schientific fiction
    end:description
    data is 
    
    end:movie
    data is 
    
    。。。。。。。。。
    。。。。。。。。。
    end:collection
    

    参考资料:
    Python的expat库可以动态解析
    python使用expat解析xml

    相关文章

      网友评论

        本文标题:用python解析xml文件

        本文链接:https://www.haomeiwen.com/subject/ycsbeftx.html