Home > Backend Development > Python Tutorial > python解析xml文件实例分析

python解析xml文件实例分析

WBOY
Release: 2016-06-10 15:11:25
Original
1163 people have browsed it

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

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

如果xml的结构如下:

<&#63;xml version="1.0" encoding="utf-8"&#63;> 
<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>

Copy after login

第三个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........................"
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template