XSLT: Remove excess whitespace characters preserving nodes

前端 未结 3 516
后悔当初
后悔当初 2021-01-16 08:06

So my problem is this. I have a transform document which is used in many places, and generically handles a lot of small formatting transforms. In one specific case, I need t

相关标签:
3条回答
  • 2021-01-16 08:21

    When you use normalize-space then only the text-value of your fragment is used and thus sub-nodes are stripped. You'd have to put the normalize-space into templates for the sub-nodes as well (those that are applied by your <xsl:apply-templates/>

    0 讨论(0)
  • 2021-01-16 08:34

    I've got two options:

    If the \n it not literal then do this:

    <xsl:template match="text()[ancestor-or-self::no_whitespace]">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>
    

    to clean up all white space at and below the no_whitespace tag.

    If the \n is a literal in the string then its get a bit more complex to get rid of the \n. Use this:

    <xsl:template name="strip_newline">
        <xsl:param name="string"/>
        <xsl:value-of select="substring-before($string,'\n')"/>
        <xsl:variable name="rhs" select="substring-after($string,'\n')"/>
        <xsl:if test="$rhs">
            <xsl:call-template name="strip_newline">
                <xsl:with-param name="string" select="$rhs"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
    
    <xsl:template match="text()[ancestor-or-self::no_whitespace]">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>
    
    <xsl:template match="text()[ancestor-or-self::no_whitespace][contains(.,'\n')]">
        <xsl:variable name="cleantext">
            <xsl:call-template name="strip_newline">
                <xsl:with-param name="string" select="."/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:value-of select="normalize-space($cleantext)"/>
    </xsl:template>
    

    In both cases, I'm assuming you already have an identity template in place elsewhere in you xsl:

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    0 讨论(0)
  • 2021-01-16 08:38

    It cound just indentation in the output. Do you have <xsl:output indent="yes"/> at the top of you xsl? Or maybe the processor is enforceing indentation. Using <xsl:output indent="no"/> should soak up all the \n and indentation.

    0 讨论(0)
提交回复
热议问题