minidom的toprettyxml()默认保留并美化原始空白节点,导致多余空行;应先调用再清理空白行,或改用ElementTree结合minidom处理。

用 minidom 的 toprettyxml() 方法确实能格式化 XML,但默认会多出空行、缩进不一致,甚至在某些版本里还会插入多余的换行——这不是 bug,是设计行为。关键是要理解它怎么工作,再针对性处理。
因为 toprettyxml() 会把文本节点(比如换行符、空格)也当成独立节点来缩进,而原始 DOM 中的换行和空白会被保留并美化,结果就是标签之间冒出大量空行。
最稳妥的做法是:先调用 toprettyxml(),再用正则或字符串处理把连续的换行压缩掉:
import xml.dom.minidom
<h1>假设 doc 是你的 Document 对象</h1><p>rough_string = doc.toprettyxml(indent=" ", encoding=None)</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1926">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680432772559.jpg" alt="Text Mark">
</a>
<div class="aritcle_card_info">
<a href="/ai/1926">Text Mark</a>
<p>处理文本内容的AI助手</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="Text Mark">
<span>113</span>
</div>
</div>
<a href="/ai/1926" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="Text Mark">
</a>
</div>
<h1>去掉只含空白(含换行)的行,保留带标签的行</h1><p>reparsed = '\n'.join([line for line in rough_string.split('\n') if line.strip()])
toprettyxml() 支持三个主要参数,用对了能省不少事:
" "(两个空格),可改成 "\t" 或 " "
"\n",Windows 下可设为 "\r\n"
"utf-8";设为 None 则返回 Unicode 字符串(推荐)如果对格式要求高,或者要频繁生成 XML,建议换用 xml.etree.ElementTree 配合 xml.dom.minidom 做最终美化,或直接用第三方库如 lxml:
# 简单又干净:ElementTree + minidom 衔接
import xml.etree.ElementTree as ET
from xml.dom import minidom
<p>root = ET.fromstring(your_xml_string)
rough = ET.tostring(root, encoding="unicode")
reparsed = minidom.parseString(rough).toprettyxml(indent=" ")
reparsed = '\n'.join([s for s in reparsed.split('\n') if s.strip()])
基本上就这些。不用强求 toprettyxml() 一步到位,加一行清理逻辑,输出就干净多了。
以上就是Python minidom怎么格式化输出XML toprettyxml方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号