python解析xml文件实例分析

yipeiwu_com7年前Python基础

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

python解析xml非常方便。在dive into python中也有讲解。

如果xml的结构如下:

<?xml version="1.0" encoding="utf-8"?> 
<books> 
  <book> 
    <author>zoer</author> 
    <title>think in java</title> 
    <content>this is a good book</content> 
  </book> 
  <book> 
    <author>naughty</author> 
    <title>gone with the wind</title> 
    <content>this is a good book 2</content> 
  </book> 
  <book> 
    <author>cc</author> 
    <content>this is a good book 3</content> 
  </book> 
</books>

第三个book是没有title标记的。由于不要相信代码输入,所以在代码中要做检查(比如说检查这里的有没有子标签)。

解析代码如下:

#coding=utf-8 
#parse all books 
#author:  naughty610 
#date:   2012-8-16 
import xml.dom.minidom 
dom = xml.dom.minidom.parse('C:/Users/naughty/Desktop/books.xml') 
root = dom.documentElement 
#获取每一个下一层节点 
for node in root.childNodes:
#这样取得的是root节点以下一层的节点,而不是root节点以下所有节点 
  #取所有非text节点 
  if node.nodeType == node.ELEMENT_NODE: 
    #取author字段 
    author=node.getElementsByTagName("author") 
    if len(author)>=1: 
      print author[0].childNodes[0].data 
    #取title字段 
    title=node.getElementsByTagName("title") 
    if len(title)>=1: 
      print title[0].childNodes[0].data 
    #取content字段 
    content=node.getElementsByTagName("content") 
    if len(content)>=1: 
      print content[0].childNodes[0].data 
    print "........................parting line........................"

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

相关文章

Python之数据序列化(json、pickle、shelve)详解

什么是序列化 什么是序列化,把程序中的对象或者变量,从内存中转换为可存储或可传输的过程称为序列化。在 Python 中,这个过程称为 pickling,在其他语言中也被称为 seria...

Python简单实现子网掩码转换的方法

本文实例讲述了Python简单实现子网掩码转换的方法。分享给大家供大家参考,具体如下: 这里实现将子网掩码长度转换为具体的子网掩码地址: def exchange_maskint(m...

Python3 列表,数组,矩阵的相互转换的方法示例

Python3 列表,数组,矩阵的相互转换的方法示例

在使用列表、数组和矩阵的过程中,经常需要相互转换。特此总结相互间转换的过程及结果,供大家参考。 第三方包:numpy     import nump...

django foreignkey(外键)的实现

django foreignkey(外键)的实现

foreignkey是一种关联字段,将两张表进行关联的方式,我们在dodels.py里写入要生成的两张表: class Usergroup(models.Model): uid...

python3中dict(字典)的使用方法示例

一、clear(清空字典内容) stu = { 'num1':'Tom', 'num2':'Lucy', 'num3':'Sam', } print(stu.clear...