python ElementTree 基本读操作示例

yipeiwu_com5年前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获取url的返回信息方法

如下所示: #!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import urllib im...

python3正则提取字符串里的中文实例

python3正则提取字符串里的中文实例

如下所示: # -*- coding: utf-8 -*- import re #过滤掉除了中文以外的字符 str = "hello,world!!%[545]你好234世界。。。"...

Python实现栈和队列的简单操作方法示例

Python实现栈和队列的简单操作方法示例

本文实例讲述了Python实现栈和队列的简单操作方法。分享给大家供大家参考,具体如下: 先简单的了解一下数据结构里面的栈和堆: 栈和队列是两种基本的数据结构,同为容器类型。两者根本的区别...

Python字符串和正则表达式中的反斜杠('\')问题详解

在Python普通字符串中 在Python中,我们用'\'来转义某些普通字符,使其成为特殊字符,比如 In [1]: print('abc\ndef') # '\n'具有换行的作用...

在Python中使用mechanize模块模拟浏览器功能

知道如何快速在命令行或者python脚本中实例化一个浏览器通常是非常有用的。 每次我需要做任何关于web的自动任务时,我都使用这段python代码去模拟一个浏览器。  ...