"""蓝色天空网 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')
本例需在 本地 Python 3 与 UTF-8 XML 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 3 与 UTF-8 XML
入口文件:projects/python-lab/python3-xml-processing.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python3-xml-processing.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 3 与 UTF-8 XML。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip