可爱的 Python:DOM 的动态性
2007-03-29 12:02:41 来源:WEB开发网将 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
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 = quot2 = quotation()
quot2.text =
"Python is not a democracy. Voting doesn't help. "+
"Crying may..."
quot2.source =
"Guido van Rossum, comp.lang.python"
# Create the DOM Builder
builder = Builder()
object_convert(builder, inst)
print
builder.document.toxml()
更多精彩
赞助商链接