Chinaunix首页 | 论坛 | 博客
  • 博客访问: 576709
  • 博文数量: 226
  • 博客积分: 10080
  • 博客等级: 上将
  • 技术积分: 1725
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-26 11:15
文章分类

全部博文(226)

文章存档

2011年(5)

2010年(64)

2009年(99)

2008年(37)

2007年(21)

我的朋友

分类: LINUX

2010-03-03 21:26:07

python ElementTree 基本读操作示例

演示用XML文件:test.xml

view plaincopy to clipboardprint?
 
 
  
    hzj 
    man 
 
 
  
    kiki 
    female 
 
 
 


 
    hzj
    man
 

 
    kiki
    female
 

1.加载xml文件

    加载XML文件共有2种方法,一是加载指定字符串,二是加载指定文件

2.获取element的方法

  a) 通过getiterator

  b) 过 getchildren

  c) find方法

  d) findall方法

示例如下:

view plaincopy to clipboardprint?
#-*- coding:utf-8 -*-  
from xml.etree import ElementTree  
def print_node(node):  
    '''''打印结点基本信息''' 
    print "==============================================" 
    print "node.attrib:%s" % node.attrib  
    if node.attrib.has_key("age") > 0 :  
        print "node.attrib['age']:%s" % node.attrib['age']  
    print "node.tag:%s" % node.tag  
    print "node.text:%s" % node.text  
def read_xml(text):  
    '''''读xml文件''' 
    # 加载XML文件(2种方法,一是加载指定字符串,二是加载指定文件)      
    # root = ElementTree.parse(r"D:\test.xml")  
    root = ElementTree.fromstring(text)  
      
    # 获取element的方法  
    # 1 通过getiterator   
    lst_node = root.getiterator("person")  
    for node in lst_node:  
        print_node(node)  
          
    # 2通过 getchildren  
    lst_node_child = lst_node[0].getchildren()[0]  
    print_node(lst_node_child)  
          
    # 3 .find方法  
    node_find = root.find('person')  
    print_node(node_find)  
      
    #4. findall方法  
    node_findall = root.findall("person/name")[1]  
    print_node(node_findall)  
      
if __name__ == '__main__':  
    # read_xml(open("test.xml").read())  
    write_xml(open("test.xml").read()) 

运行结果:

C:\WINDOWS\system32\cmd.exe /c "E:\Python25\p
=============================================
node.attrib:{'age': '18'}
node.attrib['age']:18
node.tag:person
node.text:

=============================================
node.attrib:{'age': '19', 'des': 'hello'}
node.attrib['age']:19
node.tag:person
node.text:

=============================================
node.attrib:{}
node.tag:name
node.text:hzj
=============================================
node.attrib:{'age': '18'}
node.attrib['age']:18
node.tag:person
node.text:

=============================================
node.attrib:{}
node.tag:name
node.text:kiki
Hit any key to close this window...

阅读(890) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~