Home > Backend Development > Python Tutorial > Python 解析XML文件

Python 解析XML文件

WBOY
Release: 2016-06-06 11:26:53
Original
1220 people have browsed it

Python文件:

代码如下:


#parsexml.py
#本例子参考自python联机文档,做了适当改动和添加

import xml.parsers.expat

#控制打印缩进
level = 0

#获取某节点名称及属性值集合
def start_element(name, attrs):
global level
print ' '*level, 'Start element:', name, attrs
level = level + 1

#获取某节点结束名称
def end_element(name):
global level
level = level - 1
print ' '*level, 'End element:', name

#获取某节点中间的值
def char_data(data):
if(data == '\n'):
return
if(data.isspace()):
return
global level
print ' '*level, 'Character data:', data

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
p.returns_unicode = False

f = file('sample.xml')
p.ParseFile(f)
f.close()


XML文件(sample.xml):

代码如下:




222222222
134567890


11111111
15909878909


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