简介
本系列文章主要讲解如何使用 Python3 的 lxml 库, 本篇和第二篇文章主要介绍Element
对象的接口
Element 对象
工厂函数
在 XML或HTML 中每一处尖括号代表着一个标签或者元素, lxml 库为了方便操作, 封装了Element
类, 通过Element
对象可以很方便地操作 XML 的元素
创建 Element
对象
from lxml import etree
# 创建根元素
root = etree.Element("root")
# 查看标签名
print("root.tag: ", root.tag)
打印结果
root.tag: root
添加 SubElement
对象, 组成有层级关系的 Elements
# 直接添加
root.append(etree.Element("child_1"))
# 通过工厂函数
child_2 = etree.SubElement(root, "child_2")
child_3 = etree.SubElement(root, "child_3")
将 Elements 序列化为 XML 树
xml_s = etree.tostring(root, pretty_print=True).decode('utf-8')
print("XML tree:", xml_s, sep='\n')
打印结果
XML tree:
<root>
<child_1/>
<child_2/>
<child_3/>
</root>
没有子元素时, lxml 自动生成单标签
这样我们直接通过 lxml 库创建了一个 XML 文档
列表接口
每一个 Element 对象相当于一个列表容器, 其内容为直接子元素, 操作方法与内置列表很相似
索引
child = root[0]
print("root[0]:", child.tag)
root[0]: child_1
结果为首个添加的子元素
切片
# 切片 (仅包含 child_3)
root_slice = root[-1:]
print("slice:", type(root_slice))
slice: <class 'list'>
切片的结果为内置列表
列表方法
# 查找
idx = root.index(child)
print("child idx:", idx)
# 插入
root.insert(0, etree.Element("child_0"))
# 附加
# root.append(etree.Element("child_1")) 前面已经试过了
# 删除
del root[-1]
# 追加 (补回 child_3)
root.extend(root_slice)
child idx: 0
在 root 起始位置添加了 child_0, 随后删除了 child_3, 通过 extend 在末尾补回 child_3
遍历
for ele in root:
print(ele.tag)
child_0
child_1
child_2
child_3
Element 对象与列表有一个细小的差别, Element 列表成员之间赋值, lxml 会删除赋值元素
root[0] = root[-1]
for ele in root:
print(ele.tag)
child_3
child_1
child_2
最后一个元素的位置被删除了, 这么做是避免修改其中的一个元素, 另一个元素也会相应被修改
元素关系
父元素与相邻元素
print("parent:", root is child.getparent())
# root[1] 之前是 root[0]
print("before:", root[0] is root[1].getprevious())
# root[1] 之后是 root[2]
print("after: ", root[2] is root[1].getnext())
打印结果
parent: True
before: True
after: True