python ElementTree 基本读操作示例

yipeiwu_com6年前Python基础
示例可以附件中下载
1.加载xml文件
加载XML文件共有2种方法,一是加载指定字符串,二是加载指定文件
2.获取element的方法
a) 通过getiterator
b) 过 getchildren
c) find方法
d) findall方法
示例如下:
复制代码 代码如下:

#-*- 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())

相关文章

详解python基础之while循环及if判断

 wlile循环   while True表示永远为真,不管是什么条件都会向下执行,下面是写的一个例子。 #!/usr/bin/env python age = 24        ...

Python多进程multiprocessing.Pool类详解

Python多进程multiprocessing.Pool类详解

multiprocessing模块 multiprocessing包是Python中的多进程管理包。它与 threading.Thread类似,可以利用multiprocessing.P...

Python实现统计单词出现的个数

最近在看python脚本语言,脚本语言是一种解释性的语言,不需要编译,可以直接用,由解释器来负责解释。python语言很强大,而且写起来很简洁。下面的一个例子就是用python统计单词出...

pyqt5、qtdesigner安装和环境设置教程

pyqt5、qtdesigner安装和环境设置教程

前言 最近工作需要写一个界面程序来调用摄像头并对摄像头采集的图像做一些处理。程序需要使用Python语言编写,经过调研发现PyQt5配合QtDesigner在界面程序编写方面具有功能丰富...

跟老齐学Python之有容乃大的list(1)

前面的学习中,我们已经知道了两种python的数据类型:int和str。再强调一下对数据类型的理解,这个世界是由数据组成的,数据可能是数字(注意,别搞混了,数字和数据是有区别的),也可能...