【发布时间】:2012-04-30 11:40:51
【问题描述】:
我正在寻找一些可以处理我的 xml 文档的正确缩进的 XSLT 样式表,并在http://www.printk.net/~bds/indent.html 找到了一个非常好的样式表。
希望作者不要因为这样的引用而责怪我:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="ISO-8859-1"/>
<xsl:param name="indent-increment" select="' '"/>
<xsl:template name="newline">
<xsl:text disable-output-escaping="yes">
</xsl:text>
</xsl:template>
<xsl:template match="comment() | processing-instruction()">
<xsl:param name="indent" select="''"/>
<xsl:call-template name="newline"/>
<xsl:value-of select="$indent"/>
<xsl:copy />
</xsl:template>
<xsl:template match="text()">
<xsl:param name="indent" select="''"/>
<xsl:call-template name="newline"/>
<xsl:value-of select="$indent"/>
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
<xsl:template match="text()[normalize-space(.)='']"/>
<xsl:template match="*">
<xsl:param name="indent" select="''"/>
<xsl:call-template name="newline"/>
<xsl:value-of select="$indent"/>
<xsl:choose>
<xsl:when test="count(child::*) > 0">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="*|text()">
<xsl:with-param name="indent" select="concat ($indent, $indent-increment)"/>
</xsl:apply-templates>
<xsl:call-template name="newline"/>
<xsl:value-of select="$indent"/>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:copy-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
除了一件讨厌的事情之外,它几乎可以满足我的所有需求:它使我的文档的根元素(但不是 XML 声明)缩进了奇怪的 8 个空格。结果看起来像那段标记:
<?xml version="1.0" encoding="UTF-8"?>
<database>
<books>
<book id="0">
<ISBN value="0123456789"/>
<title>Some book title Language</title>
<hardcover value="false"/>
<price value="40.46"/>
<in_stock value="100"/>
<annotation>Some annotation</annotation>
</book>
</books>
</database>`
我对 XSLT 技术相当陌生,花了很多时间试图了解如何修复它,但到目前为止还没有成功。我正在使用标准 javax.xml.transform.Transformer 类进行 XSLT 转换。您知道为什么会发生这种情况吗?
【问题讨论】:
-
我会仔细查看“换行符”模板的内容——里面有没有杂散的空白?另请注意,不需要 disable-output-escaping 属性(空格永远不会转义,因此禁用它无效),但该属性的存在表明编写代码的人不是专家。