我认为现在将 minidom API 视为 unpythonic 还为时过早。通过几个辅助函数,我们可以得到我们希望的 Pythonic,例如:
# Helper function to wrap the DOM element/attribute creation API.
def El( tag, attribs = None, text = None ):
el = doc.createElement( tag )
if text: el.appendChild( doc.createTextNode( text ))
if attribs is None: return el
for k, v in attribs.iteritems(): el.setAttribute( k, v )
return el
# Construct an element tree from the passed tree.
def make_els( parent_el, this_el, child_els ):
parent_el.appendChild( this_el )
for x in child_els:
if type( x ) is tuple:
child_el, grandchild_els = x
make_els( this_el, child_el, grandchild_els )
else:
this_el.appendChild( x )
doc.removeChild( doc.documentElement )
make_els( doc, El( 'html', { 'xmlns': 'http://www.w3.org/1999/xhtml', 'dir': 'ltr', 'lang': 'en' }), [
( El( 'head' ), [
El( 'meta', { 'http-equiv': 'Content-Type', 'content': 'text/html; charset=utf-8' }),
El( 'meta', { 'http-equiv': 'Content-Style-Type', 'content': 'text/css' }),
El( 'link', { 'rel': 'stylesheet', 'type': 'text/css', 'href': 'main.css', 'title': 'Default Stylesheet' }),
El( 'title', {}, 'XXXX XXXX XXXXr {}, {}'.format( args.xxxx, env.build_time ))
]),
( El( 'frameset', { 'cols': '20%, 80%' }), [
El( 'frame', { 'src': 'xxx_list.html', 'name': 'listframe', 'title': 'XXXX XXXX XXXX' }),
El( 'frame', { 'src': 'xxx_all_xxxx_all.html', 'name': 'regframe', 'title': 'XXX XXXX XXXX' }),
( El( 'noframes' ), [
( El( 'body' ), [
El( 'h2', {}, 'Frame Alert' ),
El( 'p', {}, 'This document is designed to be viewed using the frames feature.' )
])
])
])
])
print '\ndoc:\n', doc.toprettyxml( indent = ' ' )