简介
Element类型是一种灵活的容器对象,用于在内存中存储结构化数据。
[注意]xml.etree.ElementTree模块在应对恶意结构数据时显得并不安全。
每个element对象都具有以下属性:
1. tag:string对象,表示数据代表的种类。
2. attrib:dictionary对象,表示附有的属性。
3. text:string对象,表示element的内容。
4. tail:string对象,表示element闭合之后的尾迹。
5. 若干子元素(child elements)。
<tag attrib1=1>text</tag>tail
1 2 3 4
创建元素的方法有Element或者SubElement(),前者称作元素的构建函数(constructor),用以构建任一独存的元素;后者称作元素的制造函数(factory function),用以制造某一元素的子元素。
有了一串元素之后,使用ElementTree类来将其打包,把一串元素转换为xml文件或者从xml文件中解析出来。
若想加快速度,可以使用C语言编译的API xml.etree.cElementTree。
导入ElementTree
from xml.etree import ElementTree as ET
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
XML是中结构化数据形式,在ET中使用ElementTree代表整个XML文档,并视其为一棵树,Element代表这个文档树中的单个节点。
Element中的遍历与查询
Element.iter(tag=None):遍历该Element所有后代,也可以指定tag进行遍历寻找。
Element.findall(path):查找当前元素下tag或path能够匹配的直系节点。
Element.find(path):查找当前元素下tag或path能够匹配的首个直系节点。
Element.text: 获取当前元素的text值。
Element.get(key, default=None):获取元素指定key对应的属性值,如果没有该属性,则返回default值。
Element对象
class xml.etree.ElementTree.Element(tag, attrib={}, **extra)
tag:string,元素代表的数据种类。
text:string,元素的内容。
tail:string,元素的尾形。
attrib:dictionary,元素的属性字典。
#针对属性的操作
clear()&#x