在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

转载于:https://www.cnblogs.com/Xjng/p/3511820.html

Python中使用ElementTree解析xml相关推荐

  1. python解析xml文件elementtree_在python中使用ElementTree解析xml文件

    ElementTree是python自带的处理xml格式文件的模块,位于libxmletreeElementTree.py.这个模块有两个基本概念:Element和ElementTree. 表示整个树 ...

  2. python解析xml文件elementtree_Python中使用ElementTree解析XML示例

    [XML基本概念介绍] XML 指可扩展标记语言(eXtensible Markup Language). XML 被设计用来传输和存储数据. 概念一: 复制代码 代码如下: # foo元素的起始标签 ...

  3. python elementtree乱码_Python中使用ElementTree解析xml

    在Python中,ElementTree是我们常用的一个解析XML的模块 1.导入ElementTree模块 from xml.etree import ElementTree as ET 2.初始化 ...

  4. python 中使用ElementTree操作XML

    概述 对比其他 Python 处理 XML 的方案,xml.etree.ElementTree 模块(下文我们以 ET 来表示)相对来说比较简单,接口也较友好. 官方文档 里面对 ET 模块进行了较为 ...

  5. python中使用ElementTree 操作XML

    概述 参考elementTree的官方文档,ET 模块可以归纳为三个部分:ElementTree类,Element类以及一些操作 XML 的函数.  XML是一种固有的分层数据格式,表示它的最自然的方 ...

  6. python使用ElementTree解析XML文件

    一.将XML网页保存到本地 要加载XML文件首先应该将网页上的信息提取出来,保存为本地XML文件.抓取网页信息可以python的urllib模块. 代码如下: from urllib import u ...

  7. python【模块】xml.etree.ElementTree 解析 xml

    pytho 模块 xml.etree.ElementTree 解析 xml 文章目录 pytho 模块 xml.etree.ElementTree 解析 xml 1. 什么是 XML? 2. Elem ...

  8. python 使用ElementTree解析xml

    python 使用ElementTree解析xml 本博客转载自:https://www.cnblogs.com/hupeng1234/p/7262371.html 昨天在做解析xml的工作,试了两种 ...

  9. python中xpath定位_xpath最新:关于python中的xpath解析定位_爱安网 LoveAn.com

    关于"xpath"的最新内容 聚合阅读 这篇文章主要介绍了关于python中的xpath解析定位,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧... 这篇文章主要 ...

最新文章

  1. 区域设置 ID (LCID) 表, 及获取方法
  2. 如果每个人都是一个粒子…… | 从物理学中寻找社会规律
  3. 如何让ios app支持32位和64位?
  4. ASP.NET MVC 第一章 我们的第一个MVC例子
  5. Lambda 表达式详解~Streams API~规约操作
  6. Qt文档阅读笔记-QLibrary基本概念及实例
  7. 设计模式 - (3)抽象工厂模式(创建型)
  8. java html文件转换pdf文件_Java实现HTML转换为PDF的常见方法
  9. argb和rgb风扇的区别是什么
  10. 基于Java、MySQL的毕业设计,房屋租赁系统
  11. mac电脑怎么清空浏览器缓存?Chrome浏览器 for Mac清理缓存的方法
  12. 华东师范大学计算机学院博导,华东师范大学计算机科学与软件工程学院导师信息——陈洁...
  13. 税法18个税种全总结附记忆小口诀
  14. mysql按照年龄区间分组查询
  15. my97显示服务器时间,封装Web Uploader 上传插件、My97DatePicker、百度 编辑器 的使用 (ASP.NET MVC)...
  16. 哈希算法--暴雪的mpq技术
  17. C#分页的总页数算法
  18. AlexNet论文精读
  19. oracle设置密码复杂度、设置oracle超时退出的功能
  20. 金三银四!95后阿里P7晒出工资单:狠补了这个,真香...

热门文章

  1. YYAnimatedImageView--gif在ios14之后只能播放一次
  2. ecs服务器配置git_阿里云 ECS服务器(CentOS 7)安装和使用Gitlab教程
  3. 使用Kali官网提供的虚拟机系统
  4. 解决Kali Linux XFCE桌面Tab无法补全
  5. Xamarin Essentials教程实现数据的传输功能实例
  6. Xamarin Essentials教程使用指南针Compass
  7. 打开别人Xamarin项目找不到android.jar文件
  8. AppleWatch开发教程之调试程序使用帮助文档
  9. swift语言注册非免费苹果账号iOS游戏框架Sprite Kit基础教程
  10. python中常用的序列化模块_Python常用模块之pickle——对象序列化