Python XML 解析:事件、树与增量读取
用同一份本站 XML 对照 SAX、DOM 和 ElementTree,并验证部分读取与整文档检查的差异。
学完这一章,你能够
- 用同一份本站 XML 对照 SAX、DOM 和 ElementTree,并验证部分读取与整文档检查的差异。
先选择需要的解析结果
XML 用元素、属性与文本表示有层次的数据,并允许不同领域定义自己的元素名称。使用时先确认文档的编码、根元素、命名空间和业务规则。消息交换和文件存储是常见用途。
SAX 读取过程中调用事件处理器,适合只提取指定内容、按记录处理大文件或构造自己的对象。DOM 建立完整节点树,便于遍历和编辑。ElementTree 提供面向元素的接口,也可增量读取。速度和内存取决于文档规模、读取方式及保留的对象。
SAX 把文本交给处理器
用 make_parser 取得解析器,配置需要的功能,再注册 ContentHandler。也可用 parse 或 parseString 将输入和处理器一起交给便利函数。ErrorHandler 可记录失败位置,便于区别合法的空字段和语法错误。
startDocument 与 endDocument 表示文档边界。startElement 收到属性,可在记录开始时初始化字段。characters 的片段不按行、标签或业务字段切割,须按上下文累积。endElement 时提交完整值并清理临时状态。
本站样例对照 UTF-8 属性、缺少字段、空字段、CDATA 和混合文本。一个字段可跨多次字符回调。若只需要前两项,可主动结束查询,但这样没有检查文档尾部。独立实例用同一份带坏尾部的输入,分别观察提前取值和完整解析报错。
DOM 和 ElementTree 的编辑边界
minidom.parse 返回 Document。用 documentElement 找根节点,hasAttribute 区分缺少属性与空字符串。getElementsByTagName 返回全部匹配后代。取记录字段时限制直接子元素,按节点类型收集文本与 CDATA。
DOM 可新建或移除节点,再序列化到文件。直接用 childNodes[0] 读字段,遇到空元素或多段内容容易出错。本站保存含 & 和 < 的文本后重新解析,确认还原为相同字符。
ElementTree 的 parse 与 fromstring 返回不同类型,find 和 findall 的路径作用域也要明确。修改或删除元素时操作树中的实际对象。大文件可用 iterparse,记录完成时读取所需字段,再从父级摘下已处理节点。
分别核对格式与输入安全
三种工具都可以报告结构错误。命名空间需要按 URI 与本地名查询,默认命名空间不自动应用于未加前缀的属性。讲解实验区分 SAX 命名空间事件、DOM 的命名空间查找和 ElementTree 路径。
工程只处理本站生成的有限输入。外部实体示例使用临时目录里的无害标记,禁用 SAX 外部通用实体并核对各解析器的反应。真实业务面对未知 XML 时要限制资源、审查解析器和选项,另行验证威胁边界。
SAX 内容处理事件
| 名称 | 用途 | 版本或核对条件 |
|---|---|---|
| startDocument() | 开始解析文档时的回调。 | 可初始化状态。正常解析时先于首个元素回调。 |
| endDocument() | 成功读完文档后的回调。 | 应用提前停止或语法错误时不可假定此回调已发生。 |
| startElement(name, attrs) | 关闭命名空间处理时,收到元素名和属性映射。 | 打开命名空间时用 startElementNS,对比展开名与未加前缀的属性。 |
| characters(content) | 接收当前一段字符。 | 一个字段可能有多段回调。遇到实体、CDATA 或分段读取时,把片段累加后再提交。 |
| endElement(name) | 结束元素时的回调。 | 通常在此提交已累积字段,再恢复父级状态。 |
SAX 入口与选项
| 名称 | 用途 | 版本或核对条件 |
|---|---|---|
| make_parser(parser_list=[]) | 创建可用的 XMLReader。 | parser_list 可选,填解析器模块名,指定候选优先于默认列表。 |
| parse(filename_or_stream, handler, error_handler=...) | 从路径或文件类对象读取,事件交给 ContentHandler。 | 可指定 ErrorHandler。默认解析错误会抛出异常。函数自身不返回树。 |
| parseString(string, handler, error_handler=...) | 在内存中解析 XML 字符串或字节。 | 错误处理仍可定制。文本与自带编码声明的字节输入分别验证。 |
| setFeature(...) / setContentHandler(...) | 切换解析器选项并登记处理器。 | 命名空间和外部通用实体是独立选项。是否支持某功能取决于解析器。 |
DOM 与 ElementTree 的常见操作
| 名称 | 用途 | 版本或核对条件 |
|---|---|---|
| minidom.parse(...) | 将路径或输入流解析为 Document。 | documentElement 给出根元素。可通过上下文管理释放 DOM 结构。 |
| hasAttribute / getAttribute | 判断属性是否存在并取值。 | 缺少属性时 getAttribute 也可能得到空字符串。 |
| getElementsByTagName / childNodes | 查询后代元素并查看子节点。 | 嵌套同名字段需要限定直接子级,空元素和 CDATA 需要显式处理。 |
| ElementTree.parse / fromstring | parse 返回树,fromstring 返回根 Element。 | Element 保存标签、属性、子元素、text 与 tail。 |
| ElementTree.iterparse | 按 start 和 end 交付逐步解析结果。 | 完整记录在 end 时处理。批处理后从父级移除并清空,避免保留已处理子树。 |
对照三种 XML 解析和树编辑
"""蓝色天空网 mbsky.com | Read, edit and compare three Python XML interfaces."""
from decimal import Decimal
from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from xml.dom import Node, minidom
from xml.parsers import expat
from xml.sax import ContentHandler, SAXParseException, make_parser, parse, parseString
from xml.sax.handler import EntityResolver, ErrorHandler, feature_external_ges, feature_namespaces
from xml.etree import ElementTree as ET
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
CATALOG = Path(__file__).with_name('xml-catalog-lab.xml')
FIELDS = ('type','format','year','episodes','rating','stars','description')
EXPECTED = [
('潮汐图', ('科学','PDF','2025',None,'A','5','潮汐 & 风 <坐标> 潮头 回落')),
('巡灯记', ('纪实','EPUB',None,'3','B',None,'三次夜航。')),
('雨量簿', ('记录','CSV','2024',None,'','4','站点甲与乙。')),
('云层线索', ('观测','TXT',None,None,None,None,'没有评分字段。')),
]
BOOKS = [
('目录整理 & 检索', '吴桐', '19.90'),
('按字段读 <样本>', '陈雨', '32.05'),
]
def tree_records(root):
rows=[]
for record in root.findall('record'):
fields=[]
for field in FIELDS:
child=record.find(field)
fields.append(None if child is None else ''.join(child.itertext()))
rows.append((record.attrib['title'],tuple(fields)))
return rows
def tree_examples(data, path, folder, checks):
eq=checks.eq
root=ET.fromstring(data)
eq('fromstring returns root Element', (type(root).__name__,root.tag), ('Element','catalog'))
eq('fromstring accepts Unicode text',ET.fromstring('<r>石桥</r>').text,'石桥')
tree=ET.parse(path)
eq('parse returns ElementTree and root', (type(tree).__name__,tree.getroot().get('shelf')),
('ElementTree','海边书架'))
eq('tree find first direct child', root.find('record').get('title'),'潮汐图')
eq('tree findall direct children',len(root.findall('record')),4)
eq('tree find path locates nested child',root.find('record/format').text,'PDF')
eq('tree missing element returns None',root.find('missing'),None)
description=root.find('record/description')
eq('tree text and child tail differ', (description.text,description.find('em').tail),
('潮汐 & 风 <坐标> ',' 回落'))
eq('tree reconstructs all records including optional and blank fields',tree_records(root),EXPECTED)
def make_books():
library=ET.Element('library')
for title,author,price in BOOKS:
book=ET.SubElement(library,'book')
for tag,value in zip(('title','author','price'),(title,author,price)):
ET.SubElement(book,tag).text=value
return library
def read_books(library):
return [(b.findtext('title'), b.findtext('author'), str(Decimal(b.findtext('price'))))
for b in library.findall('book')]
library=make_books()
serialized=ET.tostring(library,encoding='utf-8')
eq('read two book records from XML bytes',read_books(ET.fromstring(serialized)),BOOKS)
destination=folder/'owned-books.xml'
ET.ElementTree(library).write(destination,encoding='utf-8',xml_declaration=True)
written=destination.read_bytes()
eq('UTF-8 declaration and escaping in saved XML',
(written.startswith(b"<?xml version='1.0' encoding='utf-8'?>"),b'&' in written,b'<' in written),
(True,True,True))
reopened=ET.parse(destination).getroot()
eq('save and parse book records roundtrip',read_books(reopened),BOOKS)
book=reopened.find('book')
book.attrib['state']='reviewed'
book.set('id','007')
title=book.find('title')
title.text='新标题 & 说明'
eq('change attributes and text', (book.attrib['state'],book.get('id'),title.text),
('reviewed','007','新标题 & 说明'))
checks.raises('remove requires the actual child object',ValueError,lambda:book.remove(ET.Element('title')))
book.remove(title)
eq('remove only the selected child', (book.find('title'),book.findtext('author')),(None,'吴桐'))
class CatalogHandler(ContentHandler):
def __init__(self):
super().__init__()
self.events=[]
self.depth=0
self.title=None
self.fields={}
self.field=None
self.chunks=[]
self.rows=[]
self.shelf=None
def startDocument(self):
self.events.append('startDocument')
def endDocument(self):
self.events.append('endDocument')
def startElement(self,name,attrs):
self.depth+=1
if self.depth==1 and name=='catalog':
self.shelf=attrs.get('shelf')
self.events.append('start catalog')
elif self.depth==2 and name=='record':
self.title=attrs['title']
self.fields={}
elif self.depth==3 and self.title is not None and name in FIELDS:
self.field=name
self.chunks=[]
def characters(self,content):
if self.field is not None:
self.chunks.append(content)
def endElement(self,name):
if self.depth==3 and name==self.field:
self.fields[name]=''.join(self.chunks)
self.field=None
elif self.depth==2 and name=='record':
self.rows.append((self.title,tuple(self.fields.get(field) for field in FIELDS)))
self.title=None
elif self.depth==1 and name=='catalog':
self.events.append('end catalog')
self.depth-=1
class TextEvents(ContentHandler):
def __init__(self):
super().__init__()
self.parts=[]
def characters(self,content):
self.parts.append(content)
def sax_examples(data,path,checks):
eq=checks.eq
parser=make_parser(['owned_missing_parser_module','xml.sax.expatreader'])
parser.setFeature(feature_namespaces,False)
parser.setFeature(feature_external_ges,False)
handler=CatalogHandler()
parser.setContentHandler(handler)
parser.parse(str(path))
eq('make_parser uses available backend',type(parser).__name__,'ExpatParser')
eq('SAX document and element callbacks in order',handler.events,
['startDocument','start catalog','end catalog','endDocument'])
eq('SAX attributes and optional records', (handler.shelf,handler.rows),('海边书架',EXPECTED))
streamed=CatalogHandler()
parse(BytesIO(data),streamed)
eq('SAX parse accepts binary stream',streamed.rows,EXPECTED)
memory=CatalogHandler()
parseString(data,memory)
eq('SAX parseString accepts XML bytes',memory.rows,EXPECTED)
unicode_events=TextEvents()
parseString('<r>石桥</r>',unicode_events)
eq('SAX parseString accepts XML text',''.join(unicode_events.parts),'石桥')
split=TextEvents()
parser=make_parser()
parser.setContentHandler(split)
for fragment in (b'<r>AB',b'C&',b'<![CDATA[<D>]]>',b'</r>'):
parser.feed(fragment)
parser.close()
eq('one SAX text field may have multiple callbacks',len(split.parts)>1,True)
eq('accumulate split characters and CDATA',''.join(split.parts),'ABC&<D>')
reports=[]
class RecordingErrors(ErrorHandler):
def fatalError(self,error):
reports.append((error.getLineNumber(),error.getColumnNumber()))
raise error
checks.raises('SAX custom handler reports malformed XML',SAXParseException,
lambda:parseString(b'<r>\n <x></r>',TextEvents(),RecordingErrors()))
eq('SAX error reports line and column', (reports[0][0],reports[0][1]>=0),(2,True))
def direct_dom_child(element,name):
return next((node for node in element.childNodes
if node.nodeType==Node.ELEMENT_NODE and node.tagName==name),None)
def dom_text(node):
if node.nodeType in (Node.TEXT_NODE,Node.CDATA_SECTION_NODE):
return node.data
if node.nodeType==Node.ELEMENT_NODE:
return ''.join(dom_text(child) for child in node.childNodes)
return ''
def dom_examples(data,path,folder,checks):
eq=checks.eq
with minidom.parse(str(path)) as doc:
root=doc.documentElement
eq('DOM root and present attribute',(root.tagName,root.hasAttribute('shelf'),root.getAttribute('shelf')),
('catalog',True,'海边书架'))
eq('DOM missing attribute needs hasAttribute',(root.hasAttribute('missing'),root.getAttribute('missing')),
(False,''))
rows=[]
for record in root.getElementsByTagName('record'):
fields=[]
for field in FIELDS:
child=direct_dom_child(record,field)
fields.append(None if child is None else dom_text(child))
rows.append((record.getAttribute('title'),tuple(fields)))
eq('DOM handles text CDATA nested elements and optional values',rows,EXPECTED)
root.setAttribute('reviewed','yes')
node=doc.createElement('note')
node.appendChild(doc.createTextNode('A & B < C'))
root.appendChild(node)
file=folder/'owned-dom-edit.xml'
file.write_bytes(doc.toxml(encoding='utf-8'))
with minidom.parse(str(file)) as reopened:
note=direct_dom_child(reopened.documentElement,'note')
eq('DOM save and reopen escaped text',
(reopened.documentElement.getAttribute('reviewed'),dom_text(note)),('yes','A & B < C'))
reopened.documentElement.removeChild(note)
eq('DOM remove child',direct_dom_child(reopened.documentElement,'note'),None)
with minidom.parseString(data) as doc:
eq('DOM parseString from bytes',doc.documentElement.getAttribute('shelf'),'海边书架')
def boundaries(folder,checks):
eq=checks.eq
namespaced=b'<r xmlns="urn:lab"><item id="007"/></r>'
root=ET.fromstring(namespaced)
eq('ElementTree namespace search and plain attribute',
(root.find('item'),root.find('m:item',{'m':'urn:lab'}).attrib),(None,{'id':'007'}))
class NamespaceHandler(ContentHandler):
def __init__(self):
super().__init__()
self.observed=[]
def startElementNS(self,name,qname,attrs):
self.observed.append((name,dict(attrs.items())))
ns=NamespaceHandler()
parser=make_parser()
parser.setFeature(feature_namespaces,True)
parser.setContentHandler(ns)
parser.parse(BytesIO(namespaced))
eq('SAX namespace callback keeps unprefixed attribute unqualified',
ns.observed[-1],(('urn:lab','item'),{(None,'id'):'007'}))
with minidom.parseString(namespaced) as doc:
item,=doc.getElementsByTagNameNS('urn:lab','item')
eq('DOM namespace lookup',item.getAttribute('id'),'007')
checks.raises('ElementTree rejects malformed syntax',ET.ParseError,lambda:ET.fromstring(b'<a><b></a>'))
checks.raises('DOM rejects malformed syntax',expat.ExpatError,lambda:minidom.parseString(b'<a><b></a>'))
# Use only an owned harmless marker to examine this runtime's external-entity behavior.
marker=folder/'owned-entity.txt'
marker.write_text('OWNED-XML-EXTERNAL-MARKER',encoding='utf-8')
entity=f'<!DOCTYPE r [<!ENTITY ext SYSTEM "{marker.as_uri()}">]><r>&ext;</r>'.encode('utf-8')
class RejectResolver(EntityResolver):
def resolveEntity(self,public_id,system_id):
raise AssertionError('resolver should not be called when external entities are disabled')
collector=TextEvents()
parser=make_parser()
parser.setFeature(feature_external_ges,False)
parser.setEntityResolver(RejectResolver())
parser.setContentHandler(collector)
parser.parse(BytesIO(entity))
eq('SAX disabled external entity did not emit marker',''.join(collector.parts),'')
checks.raises('ElementTree external entity is undefined here',ET.ParseError,lambda:ET.fromstring(entity))
with minidom.parseString(entity) as doc:
eq('DOM default parser did not emit external marker',dom_text(doc.documentElement),'')
if __name__=='__main__':
checks=Checks()
data=CATALOG.read_bytes()
with TemporaryDirectory(prefix='mbsky-python-xml-') as directory:
folder=Path(directory)
tree_examples(data,CATALOG,folder,checks)
sax_examples(data,CATALOG,checks)
dom_examples(data,CATALOG,folder,checks)
boundaries(folder,checks)
checks.finish('python3-xml-processing',interpreter=sys.version,platform=sys.platform,
expat_version=expat.EXPAT_VERSION,scope='owned UTF-8 XML and harmless local entity marker')
- 比较同一目录的属性、可选字段、字符分段和编辑结果,输出错误位置及受限实体检查。
所需环境:CPython 3.12,标准库与本站 XML 文件
当前源码 SHA256:b2a7cb17bc55efe353eaaf83687376f2680ea4008614e30fdd2940e401d7d7b9
比较提前停止和增量解析
"""蓝色天空网 | 比较 SAX 提前停止与 ElementTree 增量处理。"""
from io import BytesIO
import json
from pathlib import Path
from tempfile import TemporaryDirectory
from xml.etree import ElementTree
from xml.sax import SAXParseException, make_parser
from xml.sax.handler import ContentHandler, feature_external_ges
RECORDS = 2048
PREFIX = (b'<catalog><entry id="1" ready="yes"/>'
b'<entry id="2" ready="no"/><entry id="3" ready="yes"/>')
BAD_TAIL = PREFIX + b'<entry id="4"></catalog>'
class EnoughMatches(Exception):
"""The teaching query reached its own explicit result limit."""
class MatchIds(ContentHandler):
def __init__(self, limit=None):
super().__init__()
self.limit = limit
self.ids = []
self.document_ended = False
def startElement(self, name, attrs):
if name == 'entry' and attrs.get('ready') == 'yes':
self.ids.append(int(attrs['id']))
if self.limit is not None and len(self.ids) == self.limit:
raise EnoughMatches
def endDocument(self):
self.document_ended = True
def sax_find(data, limit=None):
handler = MatchIds(limit)
parser = make_parser()
parser.setFeature(feature_external_ges, False)
parser.setContentHandler(handler)
result = {'stopped_at_limit': False, 'parse_error': None}
with BytesIO(data) as stream:
try:
parser.parse(stream)
except EnoughMatches:
result['stopped_at_limit'] = True
except SAXParseException as error:
result['parse_error'] = {'type': type(error).__name__, 'line': error.getLineNumber(),
'column': error.getColumnNumber()}
return {**result, 'ids': handler.ids, 'document_ended': handler.document_ended}
def write_catalog(path):
with path.open('wb') as stream:
stream.write(b'<catalog>\n')
for index in range(1, RECORDS + 1):
stream.write(f'<entry id="{index}"><weight>{index % 7}</weight></entry>\n'.encode('ascii'))
stream.write(b'</catalog>\n')
def incremental_total(path):
count = total = largest_children_batch = 0
with path.open('rb') as stream:
events = ElementTree.iterparse(stream, events=('start','end'))
_, root = next(events)
for event, element in events:
if event == 'end' and element.tag == 'entry':
count += 1
total += int(element.findtext('weight'))
largest_children_batch = max(largest_children_batch, len(root))
root.remove(element)
element.clear()
return {'records': count, 'weight_sum': total, 'root_children_after_run': len(root),
'largest_children_batch_in_this_run': largest_children_batch}
def main():
prefix_only = sax_find(BAD_TAIL, limit=2)
same_document = sax_find(BAD_TAIL)
valid_document = sax_find(PREFIX + b'</catalog>')
with TemporaryDirectory(prefix='xml-stream-',dir='.') as temporary:
fixture = Path(temporary) / 'entries.xml'
write_catalog(fixture)
streamed = incremental_total(fixture)
print(json.dumps(dict(early_sax=prefix_only,full_malformed_sax=same_document,full_valid_sax=valid_document,
incremental_tree=streamed,temporary_fixture_removed=not Path(temporary).exists())))
if __name__=='__main__':
main()
- SAX 提前得到 [1, 3],全读同一错误文件则报错。增量树处理 2048 条记录,移除已处理的子元素。
所需环境:CPython 3.12,本站临时生成的 XML
当前源码 SHA256:03fac4f86a0899c5d1decf730273868ef4d2cd682f785c13066b272aa1bf0150
XML 工程下载
所需环境:CPython 3.12,标准库与本站 XML 文件
ZIP SHA256:e7bb2df2b2b9a5d69ebce5ff87b0c09b019911385242df7f1af9729394398f59
常见错误与边界
- 核对目标解释器版本、环境条件和输入后,再比较实际输出。
练习与解答
SAX 在一个元素里连续收到三个 characters 回调,应该在哪一步使用完整字段?
展开参考解答
先累加三个片段,待对应的 endElement 再合并并提交。提前停止时还需区分已取得的数据和完整的文档验证。