Section 94.1: 使用元素树打开和读取

导入 ElementTree 对象,打开相关的 .xml文件并获取根标签:

import xml.etree.ElementTree as ET
tree = ET.parse("yourXMLfile.xml")
root = tree.getroot()

在树中搜索有几种方法。第一种是迭代:

for child in root:
  print(child.tag, child.attrib)

否则,您可以像使用 list 一样引用特定位置:

print(root[0][1].text)

要按名称搜索特定标记,请使用 .find 或 .findall:

print(root.findall("myTag"))
print(root[0].find("myOtherTag"))

Section 94.2: 创建和构建 XML 文档

导入元素树模块

import xml.etree.ElementTree as ET

Element() 函数用于创建 XML 元素

p=ET.Element('parent')

用于为给定元素创建子元素的 SubElement() 函数

c = ET.SubElement(p, 'child1')

dump() 函数用于转储 xml 元素。

ET.dump(p)
# Output will be like this
#<parent><child1 /></parent>

如果要保存到文件,可使用ElementTree()函数创建一个 xml 树,然后使用write()方法保存到文件。

tree = ET.ElementTree(p)
tree.write("output.xml")

Comment()函数用于在 xml 文件中插入注释。

comment = ET.Comment('user comment')
p.append(comment) #this comment will be appended to parent element

Section 94.3: 修改 XML 文件

导入元素树模块并打开 xml 文件,获取 xml 元素

import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root=tree.getroot()
element = root[0] #get first child of root element

可通过更改字段、添加和修改属性、添加和删除子元素来操作元素对象

element.set('attribute_name', 'attribute_value') #set the attribute to xml element
element.text="string_text"

如果要删除元素,请使用 Element.remove() 方法

root.remove(element)

ElementTree.write() 方法用于将 xml 对象输出到 xml 文件。

tree.write('output.xml')

Section 94.4: 用 XPath 搜索 XML

从 2.7 版开始,ElementTree 对 XPath 查询提供了更好的支持。XPath 是一种语法,可让您像使用 SQL 在数据库中搜索一样在 xml 中进行导航。find 和 findall 函数都支持 XPath。本示例将使用下面的 xml

<Catalog>
  <Books>
    <Book id="1" price="7.95">
      <Title>Do Androids Dream of Electric Sheep?</Title>
      <Author>Philip K. Dick</Author>
    </Book>
    <Book id="5" price="5.95">
      <Title>The Colour of Magic</Title>
      <Author>Terry Pratchett</Author>
    </Book>
    <Book id="7" price="6.95">
      <Title>The Eye of The World</Title>
      <Author>Robert Jordan</Author>
    </Book>
  </Books>
</Catalog>

搜索所有图书:

import xml.etree.cElementTree as ET
tree = ET.parse('sample.xml')
tree.findall('Books/Book')

搜索书名 = "The Colour of Magic" 的书籍:

tree.find("Books/Book[Title='The Colour of Magic']")
# always use '' in the right side of the comparison

搜索 id = 5 的图书:

tree.find("Books/Book[@id='5']")
# searches with xml attributes must have '@' before the name

搜索第二本书:

tree.find("Books/Book[2]")
# indexes starts at 1, not 0

搜索最后一本书:

tree.find("Books/Book[last()]")
# 'last' is the only xpath function allowed in ElementTree

搜索所有作者:

tree.findall(".//Author")
#searches with // must use a relative path

image-20250201223046496

Section 94.5: 使用 iterparse(增量解析)打开和读取大型 XML 文件

有时,我们并不想加载整个 XML 文件来获取所需的信息。在这种情况下,如果能以增量方式加载相关部分,并在完成后删除它们,就会非常有用。使用 iterparse 函数,您可以编辑在解析 XML 时存储的元素树。

导入 ElementTree 对象:

import xml.etree.ElementTree as ET

打开 .xml 文件,遍历所有元素:

for event, elem in ET.iterparse("yourXMLfile.xml"):
  ... do something ...

或者,我们可以只查找特定事件,如开始/结束标记或命名空间。如果省略该选项(如上所述),则只返回 “结束 ”事件:

events=("start", "end", "start-ns", "end-ns")
for event, elem in ET.iterparse("yourXMLfile.xml", events=events):
  ... do something ...

下面是一个完整的示例,展示了如何在处理完内存树中的元素后将其清除:

for event, elem in ET.iterparse("yourXMLfile.xml", events=("start","end")):
  if elem.tag == "record_tag" and event == "end":
    print(elem.text)
    elem.clear()
  ... do something else ...