2010-07-22 21 views

回答

32

這種轉變:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:template match="t"> 
    <p> 
    <xsl:apply-templates/> 
    </p> 
</xsl:template> 

<xsl:template match="text()" name="insertBreaks"> 
    <xsl:param name="pText" select="."/> 

    <xsl:choose> 
    <xsl:when test="not(contains($pText, '&#xA;'))"> 
     <xsl:copy-of select="$pText"/> 
    </xsl:when> 
    <xsl:otherwise> 
     <xsl:value-of select="substring-before($pText, '&#xA;')"/> 
     <br /> 
     <xsl:call-template name="insertBreaks"> 
     <xsl:with-param name="pText" select= 
      "substring-after($pText, '&#xA;')"/> 
     </xsl:call-template> 
    </xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 
</xsl:stylesheet> 

當這個XML文檔施加:

<t>Line1 
Line2 
Line3 
</t> 

產生想要的,正確的結果:

<p>Line1<br />Line2<br />Line3<br /></p> 
+0

它不工作。我使用jquery.xslt.js來進行翻譯。你認爲這很重要嗎? – liysd 2010-07-22 15:13:40

+1

@liysd:我糾正了我的答案。現在就試試。 – 2010-07-22 15:58:02

+0

@liysd:現在,它工作。 @Dimitre:+1也因爲我喜歡這種遞歸模式。 – 2010-07-22 23:20:12