在使用Python ElementTree和minidom美化打印XML时禁用转义。
- 论坛
- 在使用Python ElementTree和minidom美化打印XML时禁用转义。
14 浏览
在使用Python ElementTree和minidom美化打印XML时禁用转义。
我正在尝试使用Python和ElementTree构建一个XML文件,然后使用minidom进行漂亮打印,按照这个代码片段。我面临的问题是,当我生成一个SubElement
时,如果字符串中包含引号,它会被转义为"
。
代码非常简单:
from xml.etree import ElementTree as et from xml.dom import minidom def prettify(elem): """Return a pretty-printed XML string for the Element.""" rough_string = et.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent="\t") top = et.Element("Base") sub = et.SubElement(top, "Sub") sub.text = 'Hello this is "a test" with quotes' print(prettify(top))
生成的XML如下:
Hello this is "a test" with quotes
是否有一种方法可以避免转义引号?