# -*- coding: cp936 -*-
#python 27
#xiaodeng
#python 之模块之 xml.dom.minidom解析xml
#http://www.cnblogs.com/coser/archive/2012/01/10/2318298.html
#python有三种方法解析XML,SAX,DOM,以及ElementTree #import xml.dom
#这里主要通过xml.dom.minidom创建xml文档,然后解析用以熟悉api
#常用方法function()
'''
minidom.parse(filename) #加载和读取xml文件
doc.documentElement #获取xml文档对象
node.getAttribute(AttributeName) #获取xml节点属性值
node.getElementsByTagName(TagName) #获取xml节点对象集合
node.childNodes #获取子节点列表
node.childNodes[index].nodeValue #获取xml节点值
node.firstChild #访问第一个节点
n.childNodes[0].data #获得文本值
node.childNodes[index].nodeValue #获取XML节点值 doc=minidom.parse(filename)
doc.toxml('utf-8') #返回Node节点的xml表示的文本
''' #test.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>
''' #解析案例
from xml.dom import minidom
doc=minidom.parse('test.xml') #parse("foo.xml")
#parseString("<foo><bar/></foo>") #实例化
root=doc.documentElement #注意没括号 #文档对象元素
print '--'*25
print root.nodeName #节点名字,collection
print root.nodeValue #节点的值,None
print root.nodeType #节点类型,1
print root.ELEMENT_NODE #
print '--'*25 #在集合中获取所有电影
nodes=root.getElementsByTagName('movie') #获取xml节点对象集合 #打印每部电影的详细信息
for n in nodes:
#print n#<DOM Element: movie at 0x1f9d968> #获得电影的title的属性值
#print n.getAttribute('title') #获取xml节点type对象的具体信息
type= n.getElementsByTagName('type')[0]
print "Type:%s" % type.childNodes[0].data##获得文本值

最新文章

  1. 推荐两款简单好用的图片放大jquery插件
  2. GIT分支管理模型
  3. Swift Swift中的反射
  4. K米评测
  5. 使用PopupWindow
  6. 备份数据库的时候设置 BufferCount 选项不正确导致 out of memory 的情况
  7. 连贯接口(fluent interface)的Java实现及应用。
  8. Ubuntu 14.04 使用的一些笔记
  9. Apache Spark源码走读之2 -- Job的提交与运行
  10. iOS网络编程同步GET方法请求编程
  11. http://jingyan.baidu.com/article/e4511cf33479812b855eaf67.html
  12. hdoj 1276 士兵队列训练问题【模拟】
  13. 给定数组A,大小为n,现给定数X,判断A中是否存在两数之和等于X
  14. javaCV开发详解之5:录制音频(录制麦克风)到本地文件/流媒体服务器(基于javax.sound、javaCV-FFMPEG)
  15. Java移位运算符详解实例
  16. 对于react中rredux的理解
  17. 基于nopcommerce b2c开源项目的精简版开发框架Nop.Framework
  18. HTTP SIP 认证
  19. Intellij idea注册码失效
  20. iframe 跨域调用父级方法的方案

热门文章

  1. 修改VIM恶心的注释自动格式化
  2. JavaScript:Date 对象
  3. Leetcode-841. 钥匙和房间
  4. 关于XSuperMES项目使用的AChartEngine图表引擎
  5. 【Java】Java-fastjson-基本使用方法
  6. form表单的reset
  7. installers PHPManager
  8. oauth2-server-php-docs 存储 学说2
  9. 从头来之【MAC下代码管理工具】
  10. 壮士断腕!WordPress宣布停止使用React