文档对象模型
xml.dom 模块对于 Python 程序员来说,可能是使用 XML 文档时功能最强大的工具。不幸的是,XML-SIG 提供的文档目前来说还比较少。W3C 语言无关的 DOM 规范填补了这方面的部分空白。但 Python 程序员最好有一个特定于 Python 语言的 DOM 的快速入门指南。本文旨在提供这样一个指南。在 上一篇专栏文章 中,某些样本中使用了样本 quotations.dtd 文件,并且这些文件可以与本文中的代码样本档案文件一起使用。
有必要了解 DOM 的确切含义。这方面,正式解释非常好:
“文档对象模型”是平台无关和语言无关的接口,它允许程序和脚本动态访问和更新文档的内容、结构和样式。可以进一步处理文档,而处理的结果也可以合并到已显示的页面中。(万维网联盟 DOM 工作组)
DOM 将 XML 文档转换成树 -- 或森林 -- 表示。万维网联盟 (W3C) 规范给出了一个 HTML 表的 DOM 版本作为例子。

如上图所示,DOM 从一个更加抽象的角度定义了一组可以遍历、修剪、改组、输出和操作树的方法,而这种方法要比 XML 文档的线性表示更为便利。
将 HTML 转换成 XML
有效的 HTML 几乎就是有效的 XML,但又不完全相同。这里有两个主要的差异,XML 标记是区分大小写的,并且所有 XML 标记都需要一个显式的结束符号(作为结束标记,而这对于某些 HTML 标记是可选的;例如: <img src="X.png" /> )。使用 xml.dom 的一个简单示例就是使用 HtmlBuilder() 类将 HTML 转换成 XML。
try_dom1.py
"""Convert a valid HTML document to XML
USAGE: python try_dom1.py < infile.html > outfile.xml
"""
import
sys
from
xml.dom
import
core
from
xml.dom.html_builder
import
HtmlBuilder
# Construct an HtmlBuilder object and feed the data to it
b = HtmlBuilder()
b.feed(sys.stdin.read())
# Get the newly-constructed document object
doc = b.document
# Output it as XML
print
doc.toxml()
HtmlBuilder() 类很容易实现它继承的部分基本 xml.dom.builder 模板的功能,它的源码值得研究。然而,即使我们自己实现了模板功能,DOM 程序的轮廓还是相似的。在一般情况下,我们将用一些方法构建一个 DOM 实例,然后对该实例进行操作。DOM 实例的 .toxml() 方法是一种生成 DOM 实例的字符串表示的简单方法(在以上的情况中,只要在生成后将它打印出来)。
将 Python 对象转换成 XML
Python 程序员可以通过将任意 Python 对象导出为 XML 实例来实现相当多的功能和通用性。这就允许我们以习惯的方式来处理 Python 对象,并且可以选择最终是否使用实例属性作为生成 XML 中的标记。只需要几行(从 building.py 示例派生出),我们就可以将 Python“原生”对象转换成 DOM 对象,并对包含对象的那些属性执行递归处理。
try_dom2.py
"""Build a DOM instance from scratch, write it to XML
USAGE: python try_dom2.py > outfile.xml
"""
import
types
from
xml.dom
import
core
from
xml.dom.builder
import
Builder
# Recursive function to build DOM instance from Python instance
defobject_convert
(builder, inst):
# Put entire object inside an elem w/ same name as the class.
builder.startElement(inst.__class__.__name__)
for
attr
in
inst.__dict__.keys():
if
attr[0] ==
'_':
# Skip internal attributes
continue
value = getattr(inst, attr)
if
type(value) == types.InstanceType:
# Recursively process subobjects
object_convert(builder, value)
else
:
# Convert anything else to string, put it in an element
builder.startElement(attr)
builder.text(str(value))
builder.endElement(attr)
builder.endElement(inst.__class__.__name__)
if
__name__ ==
'__main__':
# Create container classes
classquotations
:
pass
classquotation
:
pass
# Create an instance, fill it with hierarchy of attributes
inst = quotations()
inst.title =
"Quotations file (not quotations.dtd conformant)"
inst.quot1 = quot1 = quotation()
quot1.text =
"""'"is not a quine" is not a quine' is a quine"""
quot1.source =
"Joshua Shagam, kuro5hin.org"
inst.quot2 ='yhnnk#9b&zhnny"y.b9.b#9.gg.#yc.yc $y.n,9bj."*"jyb,9$yc 9.*/cyi9a`z+;!yb,9c 9l`."% !y99"b(:fi9"z"BWOB]\HHBH\H\NBX[\[]HH\[Y[\[HXBBBBBBWBB[\BB
BBH\ HH [][[BH[\VCBBH[[H\[H]\BXXH\H [][H]\X^JCB\HBB[CBBNBBBCBBHH[[P[
[\VJCBBB^BBBBXZBB\\[
JCBBH]\H\H][][\H\Y]B[[\H[H\XY\][H\B[]H[[Y[Y]\\^]\XK]ˊCB\]\
CBBH[ X\X\[\BBBBHBB[BB\BBBY\\K[\[\B[YJKJCBBH]HX[\[]YBBB[BB[
CBBOB]Bi9$y.!S9" 9.*#9% !y/o 9.*ghd$yn9(yge[X9%[;`*9."ac9.+yi][][:"a9kyg9l!o%ya 9.*`/9odye8 #9i9/ob&ze9l,yid#9k]9b%i9.eyamkg9. 9-exB |