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

如何使用xsltproc将XML文件缩进调整为四个空格?

可以修改为四个空格缩进,xsltproc依赖的libxslt库提供了自定义缩进空格数的扩展支持,有两种常用实现方案:

方案1:直接修改XSLT配置

在原有的<output>标签中添加indent-amount="4"属性即可,修改后的完整XSLT代码如下:

<stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform">
    <output method="xml" indent="yes" encoding="UTF-8" indent-amount="4"/>
    <strip-space elements="*"/>

    <template match="processing-instruction()|@*">
        <copy>
            <apply-templates select="node()|@*"/>
        </copy>
    </template>

    <template match="*">
        <copy>
            <apply-templates select="@*"/>
            <apply-templates>
                <sort select="name()"/>
                <sort select="@*[1]"/>
                <sort select="@*[2]"/>
                <sort select="@*[3]"/>
                <sort select="@*[4]"/>
                <sort select="@*[5]"/>
                <sort select="@*[6]"/>
            </apply-templates>
        </copy>
    </template>
</stylesheet>

说明:indent-amount是libxslt的扩展属性,仅对xsltproc等基于libxslt的处理器生效,属于非标准扩展,不会影响其他XSLT处理器的正常运行。

方案2:命令行二次格式化(无需修改XSLT)

如果不想改动原有XSLT文件,可以在转换后通过xmllint工具统一格式化缩进:

xsltproc sort.xslt 输入文件.xml | xmllint --format --indent 4 --encode UTF-8 - > 输出文件.xml

该方案不受XSLT处理器限制,适用于所有XML输出的格式化场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:54:05