Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

xslt - How can I remove whitespace when declaring an XSL variable?

I have to create an XSL variable with a choose in it. Like the following:

<xsl:variable name="grid_position">
  <xsl:choose>
    <xsl:when test="count(/Element) &gt;= 1">
      inside
    </xsl:when>
    <xsl:otherwise>
      outside
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

And later in my code, I do an xsl if:

<xsl:if test="$grid_position = 'inside'">
   {...code...}
</xsl:if>

Problem is that my variable is never = 'inside' because of the line breaks and indent. How can I remove whitespaces from my variable? I know I can remove it using disable-output-escaping="yes" when I use it in a xsl:copy-of, but it's not working on the xsl:variable tag. So how can I remove those whitespace and line breaks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's what <xsl:text> is for:

<xsl:variable name="grid_position">
  <xsl:choose>
    <xsl:when test="count(/Element) &gt;= 1">
      <xsl:text>inside</xsl:text>
    </xsl:when>
    <xsl:otherwise>
      <xsl:text>outside</xsl:text>
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

It allows you to structure your code and control whitespace at the same time.

In fact, you should stay clear of text nodes in XSL that are not wrapped in <xsl:text> to avoid these kinds of bugs in the future, too (i.e. when code gets re-formatted or re-factored later).

For simple cases, like in your sample, doing what Jim Garrison suggests is also an option.


As an aside, testing for the existence of an element with count() is superfluous. Selecting it is enough, since the empty node-set evaluates to false.

<xsl:when test="/Element">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...