Python使用xml.etree.ElementTree解析xml文件

示例一、
data.xml



保存用户的信息

jiaoshe_15
小丸子
12345678
44

上网,打游戏
我是一个来自广东深圳的女十,我期待和喜爱运动的你成为朋友


jiaoshe_12
功夫老伯
aa33678
78

功夫
我是一个老伯,我期待和喜爱运动的你成为朋友



readxml.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Created on 2010-4-14

@author: Administrator
'''
import os
import xml.etree.ElementTree as ET

#读取xml文件
def load_xml_file(filename):
root = ET.parse(filename).getroot()
#获取文件描述
intro = root.find('intro').text
print intro
all_users = root.findall('list')
for user in all_users:
head = user.find('head').text
name = user.find('name').text
sex = user.find('sex').text
print head,name,sex


if __name__ == '__main__':

workpath = os.getcwd()
# print workpath
load_xml_file(r'%s\webUI\data\data.xml' % workpath)



输出结果
保存用户的信息
jiaoshe_15 小丸子 女
jiaoshe_12 功夫老伯 男


示例二、
1、需要解析的文件app.xml







com.mysql.jdbc.Driver




jdbc:mysql://localhost:3306/tie?useUnicode=true&characterEncoding=utf-8




root



123



class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">






com/alonely/vo/User.hbm.xml





class="org.springframework.orm.hibernate3.HibernateTemplate">
























2、解析的代码etXml.py
# -*- coding:UTF-8 -*-

import xml.etree.ElementTree as ET

#获取所有节点
def getAllBean():
root = ET.parse('app.xml').getroot()
beans = root.findall('bean')

#显示所有bean
for bean in beans:
# print ET.tostring(bean, 'UTF-8')
# print '==========================================='
pass

return beans;

#获取所有property节点,以字典的的形式返回,属性名/property节点
def getAllProperty():
beans = getAllBean()
propList = {}
for bean in beans:
propertysE = bean.findall('property')
for prop in propertysE:
proname = prop.get('name')
propList[proname] = prop
# print ET.tostring(prop, 'UTF-8')
# print '==========================================='
return propList


#根据bean的属性id获取bean的class属性值
def getBeanClassAttr(beanid):
bean = getBeanById(beanid)
return bean.get('class')#获取节点属性为class的值

#根据id获取bean节点
def getBeanById(beanid):
beans = getAllBean()
for bean in beans:
id = bean.get('id')#获取属性名为id的值
if beanid == id:
return bean

#根据bean的属性id获取其所有property节点
def getPropertysByBeanid(beanid):
bean = getBeanById(beanid)
props = bean.findall('property')
return props;

#根据bean的属性id和property的名称获取实际值
def getPropertyValue(beanid,proname):
props = getPropertysByBeanid(beanid)
for prop in props:
name = prop.get('name')
if proname == name:
valueE = prop.find('value')
if valueE != None:
return valueE.text


if __name__ == '__main__':

print getPropertyValue('userService','userDAO')

你可能感兴趣的:(python)