python解析xml文件操作实例


Posted in Python onOctober 05, 2014

本文实例讲述了python解析xml文件操作的实现方法。分享给大家供大家参考。具体方法如下:

xml文件内容如下:

<?xml version="1.0" ?> 
<!--Simple xml document__chapter 8--> 
<book> 
  <title> 
    sample xml thing 
  </title> 
  <author> 
    <name> 
      <first> 
        ma 
      </first> 
      <last> 
        xiaoju 
      </last> 
    </name> 
    <affiliation> 
      Springs Widgets, Inc. 
    </affiliation> 
  </author> 
  <chapter number="1"> 
    <title> 
      First 
    </title> 
    <para> 
      I think widgets are greate.You should buy lots of them forom 
      <company> 
        Spirngy Widgts, Inc 
      </company> 
    </para> 
  </chapter> 
</book>

python代码:

from xml.dom import minidom, Node 
import re, textwrap 
 
class SampleScanner: 
  """""" 
 
  def __init__(self, doc): 
    """Constructor""" 
    assert(isinstance(doc, minidom.Document)) 
    for child in doc.childNodes: 
      if child.nodeType == Node.ELEMENT_NODE and \ 
        child.tagName == "book": 
        self.handle_book(child) 
         
  def handle_book(self, node): 
     
    for child in node.childNodes: 
      if child.nodeType != Node.ELEMENT_NODE: 
        continue 
      if child.tagName == "title": 
        print "Book titile is:", self.gettext(child.childNodes) 
      if child.tagName == "author": 
        self.handle_author(child) 
      if child.tagName == "chapter": 
        self.handle_chapter(child) 
         
  def handle_chapter(self, node): 
    number = node.getAttribute("number") 
    print "number:", number 
    title_node = node.getElementsByTagName("title") 
    print "title:", self.gettext(title_node) 
     
    for child in node.childNodes: 
      if child.nodeType != Node.ELEMENT_NODE: 
        continue 
      if child.tagName == "para": 
        self.handle_chapter_para(child) 
         
  def handle_chapter_para(self, node): 
    company = "" 
    company = self.gettext(node.getElementsByTagName("company")) 
    print "chapter:para:company", company 
     
         
  def handle_author(self, node): 
    for child in node.childNodes: 
      if child.nodeType != Node.ELEMENT_NODE: 
        continue 
      if child.tagName == "name": 
        self.handle_author_name(child) 
      if child.tagName == "affiliation": 
        print "affiliation:", self.gettext(child.childNodes) 
         
  def handle_author_name(self, node): 
    first = "" 
    last = "" 
    for child in node.childNodes: 
      if child.nodeType != Node.ELEMENT_NODE: 
        continue 
      if child.tagName == "first": 
        first = self.gettext(child.childNodes) 
      if child.tagName == 'last': 
        last = self.gettext(child.childNodes) 
         
    print "firstname:%s,lastname:%s" % (first, last) 
     
         
  def gettext(self, nodelist): 
    retlist = [] 
    for node in nodelist: 
      if node.nodeType == Node.TEXT_NODE: 
        retlist.append(node.wholeText) 
      elif node.hasChildNodes: 
        retlist.append(self.gettext(node.childNodes)) 
         
    return re.sub('\s+', " ", ''.join(retlist)) 
   
         
if __name__=="__main__": 
  doc = minidom.parse("simple.xml") 
  sample = SampleScanner(doc)

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python编写的最短路径算法
Mar 25 Python
Python实现屏幕截图的代码及函数详解
Oct 01 Python
python利用拉链法实现字典方法示例
Mar 25 Python
Python中字典的浅拷贝与深拷贝用法实例分析
Jan 02 Python
用Django实现一个可运行的区块链应用
Mar 08 Python
Pycharm无法显示动态图片的解决方法
Oct 28 Python
Pycharm之快速定位到某行快捷键的方法
Jan 20 Python
pandas修改DataFrame列名的实现方法
Feb 22 Python
python实现递归查找某个路径下所有文件中的中文字符
Aug 31 Python
Pandas时间序列:重采样及频率转换方式
Dec 26 Python
python pandas移动窗口函数rolling的用法
Feb 29 Python
PyInstaller将Python文件打包为exe后如何反编译(破解源码)以及防止反编译
Apr 15 Python
python写xml文件的操作实例
Oct 05 #Python
python实现上传样本到virustotal并查询扫描信息的方法
Oct 05 #Python
python实现计算资源图标crc值的方法
Oct 05 #Python
python求crc32值的方法
Oct 05 #Python
Python获取文件ssdeep值的方法
Oct 05 #Python
python获取Linux下文件版本信息、公司名和产品名的方法
Oct 05 #Python
python获取文件版本信息、公司名和产品名的方法
Oct 05 #Python
You might like
PHP 使用pcntl和libevent 实现Timer功能
2013/10/27 PHP
php生成Android客户端扫描可登录的二维码
2016/05/13 PHP
CI框架扩展系统核心类的方法分析
2016/05/23 PHP
PHP多线程模拟实现秒杀抢单
2018/02/07 PHP
PHP获取php,mysql,apche的版本信息及更多服务器信息
2021/03/09 PHP
限制文本字节数js代码
2007/03/06 Javascript
Extjs 几个方法的讨论
2010/01/28 Javascript
Eval and new funciton not the same thing
2012/12/27 Javascript
jquery Validation表单验证使用详解
2020/09/12 Javascript
jquery带翻页动画的电子杂志代码分享
2015/08/21 Javascript
jquery拖拽效果完整实例(附demo源码下载)
2016/01/14 Javascript
基于Bootstrap的后台管理面板 Bootstrap Metro Dashboard
2016/06/17 Javascript
jQuery事件绑定用法详解
2016/09/08 Javascript
JS日程管理插件FullCalendar中文说明文档
2017/02/06 Javascript
使用Nodejs连接mongodb数据库的实现代码
2017/08/21 NodeJs
通过源码分析Vue的双向数据绑定详解
2017/09/24 Javascript
老生常谈JavaScript面向对象基础与this指向问题
2017/10/16 Javascript
vue使用transition组件动画效果的实例代码
2021/01/28 Vue.js
[50:38]DOTA2-DPC中国联赛 正赛 Phoenix vs CDEC BO3 第二场 3月7日
2021/03/11 DOTA
python网络编程学习笔记(六):Web客户端访问
2014/06/09 Python
简单理解Python中的装饰器
2015/07/31 Python
python 读取txt,json和hdf5文件的实例
2018/06/05 Python
在Pycharm中项目解释器与环境变量的设置方法
2018/10/29 Python
Python数据结构之栈、队列及二叉树定义与用法浅析
2018/12/27 Python
python3+django2开发一个简单的人员管理系统过程详解
2019/07/23 Python
python进阶之自定义可迭代的类
2019/08/20 Python
python+OpenCV实现车牌号码识别
2019/11/08 Python
利用CSS3实现炫酷的飞机起飞动画
2016/09/17 HTML / CSS
信号量和自旋锁的区别?如何选择使用?
2015/09/08 面试题
最新大学职业规划书范文
2013/12/30 职场文书
小学语文教学反思
2014/02/10 职场文书
暑期培训班招生方案
2014/08/26 职场文书
2015年试用期工作总结
2014/12/12 职场文书
个人廉洁自律总结
2015/03/06 职场文书
如何使用php生成zip压缩包
2021/04/21 PHP
python基础之//、/与%的区别详解
2022/06/10 Python