【问题标题】:How to indent XML by four spaces with xsltproc?如何使用 xsltproc 将 XML 缩进四个空格?
【发布时间】:2021-12-25 21:27:40
【问题描述】:

使用<output method="xml" indent="yes" encoding="UTF-8"/> xsltproc 生成缩进两个空格的 XML 文件。是否可以将其更改为四个空格? Full XSLT:

<stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform">
    <output method="xml" indent="yes" encoding="UTF-8"/>
    <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>

【问题讨论】:

  • 一些 XSLT 处理器允许 xsl:output 的专有扩展属性,比如我认为的 Xalan 或 Saxon,您可以在其中设置缩进量和/或字符。我不知道 xsltproc 是否允许,它的 manpage 是怎么说的?
  • 对于 Saxon 9 或 10(不幸的是只有 PE 或 EE 版本),您可以设置例如&lt;xsl:output method="xml" indent="yes" saxon:indent-spaces="8"/&gt;(声明了xmlns:saxon="http://saxon.sf.net/")来定义识别量。但我认为 Saxon(包括 HE)中的默认值是 4,所以如果这是您想要的缩进量,也许使用 Saxon 而不是 xsltproc 会有所帮助。
  • 附带说明,XSLT/XPath 中没有定义属性的顺序,因此&lt;sort select="@*[1]"/&gt; 可以使任何属性节点成为排序键。
  • @MartinHonnen 我认为it 是我能以尽可能可重现的方式对 XML 文件进行排序的最好方法。如果在 XSLT 1.1 中完全可以按属性名称和值进行排序,那么知道这一点会很有趣。例如,This 不起作用。
  • 我认为您无法控制xsltproc 中的缩进量——既不能通过样式表也不能通过命令本身。但是应该可以将结果通过管道传输到tidy(虽然还没有测试过)。 --附言当然可以按名称指定的属性进行排序。我建议您将其作为一个单独的问题发布,而不是在 cmets 中讨论。

标签: xml xslt


【解决方案1】:

现在我已经对此进行了测试,我可以声明它可以工作(在 macOS 10.13.6 上):

xsltproc '/path/to/stylesheet.xsl' '/path/to/input.xml' | tidy -i -xml --indent-spaces 4

请注意,这会重新格式化转换结果 - 因此样式表是否缩进无关紧要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2015-10-23
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多