<!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- this content will be automatically generated across all content areas -->
<!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
级别: 初级
David Mertz 博士 (mertz@gnosis.cx), 总裁, Gnosis Software, Inc.
<!--START RESERVED FOR FUTURE USE INCLUDE FILES--><!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters --> <!--END RESERVED FOR FUTURE USE INCLUDE FILES--> 什么是 Python?什么是 XML?
Python 是由 Guido van Rossum 开发的可免费获得的高级解释型语言。其语法简单易懂,而其面向对象的语义功能强大,却又灵活随意。Python 几乎适用于每一种计算机平台,并且在平台间具有很强的可移植性。
XML 是“标准通用标记语言”(SGML) 的一种简化版本。通过一种特殊的文档类型 HTML,您也许非常熟悉 SGML。XML 文档与 HTML 一样,都是由散布于文本中的、以尖括号括起的标记确定其结构的文本组成的。但 XML 包含了许多系统标记,它们使 XML 可以用于多种用途:杂志文章和用户文档、结构化数据的文件(如 CSV 和 EDI 文件)、程序间中间通信的消息、建筑图纸(如 CAD 格式)以及许多其它用途。可以创建一组标记,以生成任何一种您想要表达的结构化信息,这就是为什么 XML 会逐渐流行,成为表示各种信息的公共标准。
回页首
文档对象模型
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
def
object_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
class
quotations
:
pass
class
quotation
:
pass
# Create an instance, fill it with hierarchy of attributes
重新安排 DOM 树
DOM 的一大优点是它可以让程序员以非线性方式对 XML 文档进行操作。由相匹配的开/关标记括起的每一块都只是 DOM 树中的一个“节点”。当以类似于列表的方式维护节点以保留顺序信息时,则顺序并没有什么特殊之处,也并非不可改变。我们可以轻易地剪下某个节点,嫁接到 DOM 树的另一个位置(如果 DTD 允许,甚至嫁接到另一层上)。或者添加新的节点、删除现有节点,等等。
try_dom4.py
"""Manipulate the arrangement of nodes in a DOM object
"""
from
try_dom3
import
*
#-- Var 'doc' will hold the single <quotations> "trunk"
doc = dom_obj.get_childNodes()[0]
#-- Pull off all the nodes into a Python list
# (each node is a <quotation> block, or a whitespace text node)
nodes = []
while
1:
try
: node = doc.removeChild(doc.get_childNodes()[0])
except
:
break
nodes.append(node)
#-- Reverse the order of the quotations using a list method
# (we could also perform more complicated operations on the list:
# delete elements, add new ones, sort on complex criteria, etc.)
nodes.reverse()
#-- Fill 'doc' back up with our rearranged nodes
for
node
in
nodes:
# if second arg is None, insert is to end of list
doc.insertBefore(node, None)