第七章:数据持久存储与交换-xml.etree.ElementTree:XML操纵API-美观打印XML

7.5.9 美观打印XML
ElementTree不会通过格式化tostring()的输出来提高可读性,因为增加额外的空白符会改变文档的内容。为了让输出更易读,后面的例子将使用xml.dom.minidom解析XML,然后使用它的toprettyxml()方法。

# ElementTree_pretty.py

from xml.etree import ElementTree
from xml.dom import minidom

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem,'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

更新后,这个例子如以下代码清单所示:

from xml.etree.ElementTree import Element,SubElement,Comment
from ElementTree_pretty import prettify

top = Element('top')

comment = Comment('Generared for PyMOTW')
top.append(comment)

child = SubElement(top,'child')
child.text = 'This child contains text.'

child_with_tail = SubElement(top,'child_with_tail')
child_with_tail.text = 'This child has text.'
child_with_tail.tail = 'And "tail" text.'

child_with_entity_ref = SubElement(top,'child_with_entity_ref')
child_with_entity_ref.text = 'This & That'

print(prettify(top))

输出也会更易读。
运行结果:
在这里插入图片描述
除了增加用于格式化的额外空白符,xml.dom.minidom美观打印器还会向输出增加一个XML声明。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值