Python解析xml文件(一)

来源:互联网 发布:变形金刚 能量矩阵 编辑:程序博客网 时间:2024/06/06 04:19
解析xml文件:
思路:
一、首先获取需要解析的文档的
二、获取解析的文档中的所有的节点元素
三、根据需要调用相关的API获取相应的信息

Python中的xml.dom.minidom模块是用来处理xml文件的,所以在处理xml文件的时候需要把这个模块引入进来

首先写一个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>

获取标签属性:
# -*- coding: UTF-8 -*-from xml.dom.minidom import parseimport xml.dom.minidom# 使用minidom解析器打开 XML 文档DOMTree = xml.dom.minidom.parse("a.xml")#获取文件中的节点元素collection = DOMTree.documentElement#nodeName节点的名字print collection.nodeName#nodeValue是结点的值,只对文本结点有效print collection.nodeValue#nodeType是结点的类型print collection.nodeType#ELEMENT_NODE节点的类型之一print collection.ELEMENT_NODE

0 0