我有一个类似这样的 xml 文件:
<Messages>
error message 1
error message 2
</Messages>
我希望输出为:
Error 1:
error message 1
Error 2:
error message 2
我使用的是 xslt 1.0,我尝试过:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="Messages">
<h3>Error 1:</h3>
<xsl:value-of select="substring-before(./text(), ' ')"/>
<h3>Error 2:</h3>
<xsl:value-of select="substring-after(./text(), ' ')"/>
</xsl:template>
</xsl:stylesheet>
但是它什么也没给我返回...有人可以帮我解决这个问题吗?谢谢!
最佳答案
您可以使用这个递归模板来实现:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="Messages" name="outputError">
<xsl:param name="index" select="1"/>
<xsl:param name="source" select="text()"/>
<xsl:variable name="thisLine" select="normalize-space(substring-before($source, ' '))"/>
<xsl:variable name="theRest" select="substring-after($source, ' ')"/>
<xsl:choose>
<xsl:when test="$thisLine">
<h3>Error <xsl:value-of select="$index"/>:</h3>
<span><xsl:value-of select="$thisLine"/></span>
<xsl:call-template name="outputError">
<xsl:with-param name="index" select="$index + 1"/>
<xsl:with-param name="source" select="$theRest"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="$theRest">
<xsl:call-template name="outputError">
<xsl:with-param name="index" select="$index"/>
<xsl:with-param name="source" select="$theRest"/>
</xsl:call-template>
</xsl:when>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
我将实际错误包装在 <span>
中元素只是为了清楚地将它们与空格分开,你当然可以使用 <p>
, <div>
如果您愿意,也可以根本没有任何元素。
关于xml - 如何使用 xslt 1.0 逐行输出文本节点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071392/