You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python生成的XML文件设置正确缩进?

解决XML输出无缩进的问题

方法一:直接用BeautifulSoup的prettify()方法

无需额外依赖,BeautifulSoup自带格式化输出能力,替换原有encode方法为prettify即可:

export = s.post(url, params=params)
soup = BeautifulSoup(export.text, features='xml')

with open('exit.xml', 'wb') as f_out:
    # 生成带缩进的XML并指定编码
    f_out.write(soup.prettify('utf-8'))

执行后生成的XML会自动带有缩进,完全匹配你期望的格式。

方法二:修正xmlformatter的参数配置

你之前的参数存在两处问题:

  • indent="1"需改为整数类型1,而非字符串
  • 若期望用空格缩进,需将indent_char="\t"替换为空格(比如" "对应两个空格缩进)

修正后的代码:

import xmlformatter

formatter = xmlformatter.Formatter(
    indent=2,
    indent_char=" ",
    encoding_output="utf-8",
    preserve=["literal"]
)
formatter.format_file("exit.xml")

方法三:使用Python标准库xml.etree.ElementTree

依赖内置库即可完成格式化,无需安装第三方包:

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

export = s.post(url, params=params)
# 解析XML内容
root = ET.fromstring(export.text)
# 生成带缩进的XML字符串
rough_string = ET.tostring(root, 'utf-8')
reparsed = minidom.parseString(rough_string)
pretty_xml = reparsed.toprettyxml(indent="  ")

# 写入文件并过滤多余空行
with open('exit.xml', 'w', encoding='utf-8') as f_out:
    filtered_lines = [line for line in pretty_xml.split('\n') if line.strip()]
    f_out.write('\n'.join(filtered_lines))

内容的提问来源于stack exchange,提问作者clemdcz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:10:37