zoukankan      html  css  js  c++  java
  • python 解析xml

      在工作中很多时候都要用到xml,使用这个时候难免会设计到解析他,然后就研究了一下python解析xml问题,看了很多东西,python有很多解析xml的包,但是也折腾我好一段时间,最后选择了这个方法。大家可以参考一下。下面这个是原xml文件,需要解析出来。不过我弄得还不够完整哈,可以一起讨论。

    <?xml version="1.0" encoding="utf-8"?>
    <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>

    解析这个的代码直接贴出来:

    #-*- coding:utf-8 -*-
    #from xml.etree import ElementTree
    #from xml.dom import minidom
    #import xml.dom.minidom
    import xml.etree.cElementTree as ET
    def element_xml():
        tree = ET.ElementTree(file='sax.xml')
        title = tree.getroot()
        print title.tag,title.attrib
        root = tree.iter()
        for i in root:
            if i.tag ==None:
                print i.attrib
            print i.tag,'==',i.text
            #print i.tag,i.attrib
    
    element_xml()
    

      开始的几个包都是研究的,但是一直不能成功,主要是没能够全部解析出来,要么解析一部分要么解析不对,最后发现这个很快都解析出来了!

  • 相关阅读:
    Spring Boot 使用 Dev-tool 热部署
    Spring Boot 上传文件
    Spring Boot 目录文件结构
    Spring MVC 文件上传
    Spring MVC 混合使用多种视图技术
    XmlViewResolver 和 ResourceBundleViewResolver
    XML 和 Json
    Excel 和 PDF
    04-树5 Root of AVL Tree (25 分)
    04-树4 是否同一棵二叉搜索树 (25 分)
  • 原文地址:https://www.cnblogs.com/Mushishi_xu/p/4711263.html
Copyright © 2011-2022 走看看