Python中使用ElementTree解析xml
在Python中,ElementTree是我们常用的一个解析XML的模块
1.导入ElementTree模块
from xml.etree import ElementTree as ET
2.初始化一个ElementTree类。初始化ElementTree类常用两种方式:一种通过xml文件,一种通过字符串。
#通过xml文件初始化,test.xml是根文件夹的一个xml文件
myET=ET.parse("test.xml")
#通过字符串初始化
xml="<xml><name>张三</name><age>21</age></xml>"
myET=ET.XML(xml)
3.查找对象
getchildren()方法会返回根节点包含的所有子节点,返回类型为ElementTree列表
find(match)方法可以根据节点名称来寻找节点内容
print myET.getchildren()[0].text
print myET.find("name").text
两行代码输出的结果都是 张三
4.添加子节点
通过append方法添加子节点
sexET=ET.XML("<sex>男</sex>")
myET.append(sexET)
5.删除子节点
通过remove方法删除子节点
ageET=myET.find("age")
myET.remove(ageET)
6.修改内容
#修改内容
myET.find("name").text="李四"
#修改标签
myET.find("name").tag="person"
7.转换成字符串
tostring()方法可以将ElementTree对象转换成字符串
第一个参数是ElementTree对象,第二个参数是编码方式,可以缺省
ET.tostring(myET,"utf-8")
ElementTree其他方法或属性:
- tag
- A string identifying what kind of data this element represents (the element type, in other words).
- text
- The text attribute can be used to hold additional data associated with the element. As the name implies this attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found between the element tags.
- tail
- The tail attribute can be used to hold additional data associated with the element. This attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found after the element’s end tag and before the next tag.
- attrib
- A dictionary containing the element’s attributes. Note that while the attrib value is always a real mutable Python dictionary, an ElementTree implementation may choose to use another internal representation, and create the dictionary only if someone asks for it. To take advantage of such implementations, use the dictionary methods below whenever possible.
The following dictionary-like methods work on the element attributes.
- clear()
- Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to None.
- get(key,default=None)
-
Gets the element attribute named key.
Returns the attribute value, or default if the attribute was not found.
- items()
- Returns the element attributes as a sequence of (name, value) pairs. The attributes are returned in an arbitrary order.
- keys()
- Returns the elements attribute names as a list. The names are returned in an arbitrary order.
- set(key,value)
- Set the attribute key on the element to value.
The following methods work on the element’s children (subelements).
- append(subelement)
- Adds the element subelement to the end of this elements internal list of subelements.
- extend(subelements)
-
Appends subelements from a sequence object with zero or more elements. RaisesAssertionError if a subelement is not a valid object.
New in version 2.7.
- find(match)
- Finds the first subelement matching match. match may be a tag name or path. Returns an element instance orNone.
- findall(match)
- Finds all matching subelements, by tag name or path. Returns a list containing all matching elements in document order.
- findtext(match,default=None)
- Finds text for the first subelement matching match. match may be a tag name or path. Returns the text content of the first matching element, ordefault if no element was found. Note that if the matching element has no text content an empty string is returned.
- getchildren()
-
Deprecated since version 2.7:Uselist(elem) or iteration.
- getiterator(tag=None)
-
Deprecated since version 2.7:Use methodElement.iter() instead.
- insert(index,element)
- Inserts a subelement at the given position in this element.
- iter(tag=None)
- Creates a tree iterator with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.
- iterfind(match)
-
Finds all matching subelements, by tag name or path. Returns an iterable yielding all matching elements in document order.
New in version 2.7.
- itertext()
-
Creates a text iterator. The iterator loops over this element and all subelements, in document order, and returns all inner text.
New in version 2.7.
- makeelement(tag,attrib)
- Creates a new element object of the same type as this element. Do not call this method, use theSubElement() factory function instead.
- remove(subelement)
- Removes subelement from the element. Unlike the find* methods this method compares elements based on the instance identity, not on tag value or contents.
参考:http://www.cnblogs.com/ifantastic/archive/2013/04/12/3017110.html
http://docs.python.org/2/library/xml.etree.elementtree.html
Python中使用ElementTree解析xml的更多相关文章
- java中采用dom4j解析xml文件
一.前言 在最近的开发中用到了dom4j来解析xml文件,以前听说过来解析xml文件的几种标准方式:但是从来的没有应用过来,所以可以在google中搜索dmo4j解析xml文件的方式,学习一下dom4 ...
- 转:在java中使用dom4j解析xml
JAVA 使用Dom4j 解析XML Java DOM4J Parser - Parse XML Document Dom4j下载及使用Dom4j读写XML简介 在java中使用dom4j解析xml ...
- julia与python中的列表解析.jl
julia与python中的列表解析.jl #=julia与python中的列表解析.jl 2016年3月16日 07:30:47 codegay julia是一门很年轻的科学计算语言 julia文档 ...
- Python中的列表解析和生成器表达式
Python中的列表解析和生成器表达式 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.列表解析案例 #!/usr/bin/env python #_*_coding:utf-8 ...
- 第14.12节 Python中使用BeautifulSoup解析http报文:使用select方法快速定位内容
一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>和<第14.11节 Python中使用BeautifulSo ...
- 第14.11节 Python中使用BeautifulSoup解析http报文:使用查找方法快速定位内容
一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>介绍了BeautifulSoup对象的主要属性,通过这些属性可以访 ...
- [python]使用ElementTree解析XML【译】
19.7 The ElementTree XML API 源码:Lib/xml/etree/ElementTree.py Element类型是一个灵活的容器对象,设计出来是用于存储有层次的数据结构到内 ...
- python XML文件解析:用ElementTree解析XML
Python标准库中,提供了ET的两种实现.一个是纯Python实现的xml.etree.ElementTree,另一个是速度更快的C语言实现xml.etree.cElementTree.请记住始终使 ...
- ZH奶酪:Python使用ElementTree解析XML【译】
19.7. xml.etree.ElementTree — The ElementTree XML API 源代码: Lib/xml/etree/ElementTree.py Element类型是一种 ...
随机推荐
- 设置N秒后执行某个方法或函数
设置N秒后执行一个函数,最常用的是设置一个定时器,今天刚看到有这样一个函数,感觉还是比较简单实用的,就先记下来,免得忘记了. 5秒后执行pushSecondController这个函数 [self p ...
- (转)fastdfs group通过添加硬盘扩容
通过给group的机器添加硬盘的方式,实现某个group的扩容. fastdfs在一台服务器支持多个store_path,每个store_path指向一个存储路径.url “M00/3F/E1/oYY ...
- spring+ibatis环境搭建
简单的spring+ibatis入门实例:ibatis是一种半自动化的持久层框架,它介于JDBC和hibernate之间,使用比较灵活. 一:目录结构 二:需要导入的jar包: 所有的第三方jar包都 ...
- url解析
window.onload=function(){ var url="http://www.qq.com/index.html?key1=1&key2=2&key3=3&qu ...
- Matlab图像函数之pie
一.pie pie用于描绘平面饼图. (1)pie(X) 利用向量X中的数据描绘饼图. 例如: X = [1, 1, 2, 2, 3, 4, 5]; pie(X) 得到 注意,X中的数据被看做频数,饼 ...
- centos 7访问windows共享文件夹
1. 首先centos要能识别win7的文件系统ntfs,原版的centos是不支持NTFS格式的文件系统,因此需要安装ntfs支持软件包,我使用的是rpmforge软件库,在此处http://pkg ...
- BFC引发的关于position的思考
BFC布局规则: 内部的Box会在垂直方向,一个接一个地放置. Box垂直方向的距离由margin决定.属于同一个BFC的两个相邻Box的margin会发生重叠 每个元素的margin box的左边, ...
- css扁平化博客学习总结(三)header代码实现
页头.banner.正文.页脚的宏观布局 1.布局顺序的重要性: 由大到小,着眼最大的部分,慢慢细分. <body> <header><!-- 页头开始 --> & ...
- ClassLoader和Reflect
什么情况下使用ClassLoader来加载类?其实这个问题应该问,什么时候使用import来加载类,不能使用import的,就只能使用ClassLoader了. 使用import的条件: 1.必须是存 ...
- GIT学习(二)
学习地址: http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 常用git命令: 1. ...