我想为XSLT中的文本输出生成换行符。什么好主意吗?
当前回答
以下XSL代码将产生换行符(换行符):
<xsl:text>
</xsl:text>
对于回车,使用:
<xsl:text>
</xsl:text>
其他回答
根据我的经验,我注意到在<xsl:variable>子句内生成新行是行不通的。 我想做的是:
<xsl:variable name="myVar">
<xsl:choose>
<xsl:when test="@myValue != ''">
<xsl:text>My value: </xsl:text>
<xsl:value-of select="@myValue" />
<xsl:text></xsl:text> <!--NEW LINE-->
<xsl:text>My other value: </xsl:text>
<xsl:value-of select="@myOtherValue" />
</xsl:when>
</xsl:choose>
<xsl:variable>
<div>
<xsl:value-of select="$myVar"/>
</div>
我试图在“新行”(空的<xsl:text>节点)中放入的任何东西都不起作用(包括本页中大多数更简单的建议),更不用说HTML在那里不起作用的事实,所以最终我不得不将其分割为2个变量,在<xsl:variable>作用域之外调用它们,并在它们之间放置一个简单的<br/>,即:
<xsl:variable name="myVar1">
<xsl:choose>
<xsl:when test="@myValue != ''">
<xsl:text>My value: </xsl:text>
<xsl:value-of select="@myValue" />
</xsl:when>
</xsl:choose>
<xsl:variable>
<xsl:variable name="myVar2">
<xsl:choose>
<xsl:when test="@myValue != ''">
<xsl:text>My other value: </xsl:text>
<xsl:value-of select="@myOtherValue" />
</xsl:when>
</xsl:choose>
<xsl:variable>
<div>
<xsl:value-of select="$myVar1"/>
<br/>
<xsl:value-of select="$myVar2"/>
</div>
是的,我知道,这不是最复杂的解决方案,但它是有效的,只是分享我对xsl的挫折经验;)
<xsl:text xml:space="preserve">
</xsl:text>
<xsl:text> </xsl:text>
参见示例
<xsl:variable name="module-info">
<xsl:value-of select="@name" /> = <xsl:value-of select="@rev" />
<xsl:text> </xsl:text>
</xsl:variable>
如果你把它写在文件中。
<redirect:write file="temp.prop" append="true">
<xsl:value-of select="$module-info" />
</redirect:write>
这个变量将生成一个新的行文件,如下:
commons-dbcp_commons-dbcp = 1.2.2
junit_junit = 4.4
org.easymock_easymock = 2.4
我不能只使用<xsl:text>
</xsl:text>方法,因为如果使用XSLT格式化XML文件,实体就会消失。所以我不得不使用一种稍微迂回的方法来使用变量
<xsl:variable name="nl" select="' '"/>
<xsl:template match="/">
<xsl:value-of select="$nl" disable-output-escaping="no"/>
<xsl:apply-templates select="*"/>
</xsl:template>
我最喜欢的方法如下:
<xsl:stylesheet>
<xsl:output method='text'/>
<xsl:variable name='newline'><xsl:text>
</xsl:text></xsl:variable>
<!-- note that the layout there is deliberate -->
...
</xsl:stylesheet>
然后,无论何时你想输出换行符(也许在csv中),你都可以输出如下内容:
<xsl:value-of select="concat(elem1,elem2,elem3,$newline)" />
我在从xml输入输出sql时使用过这种技术。事实上,我倾向于为逗号、引号和换行符创建变量。