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
1.4k views
in Technique[技术] by (71.8m points)

xml - XSLT: <xsl:strip-space> does not work

I have a servlet filter in my application that intercepts all the incoming requests and tries to strip the whitespaces from the incoming XML and write the resulting 'clean' XML to the response. I am using XSLT to achieve this. Please see the XSLT below:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="@*|node()">
<xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

However, this is not working as expected. The resulting XML is the same as the original XML (despite of using the <xsl:strip-space elements="*"/> in the stylesheet.

Please help me getting this right.

Regards,
- Ashish

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It is not clear what you intend to get as an output, and what you expect from xsl:strip-whitespace in the first place. But one thing to note is that it doesn't strip all whitespace, but only that which is deemed insignificant under the "usual" rules. In particular, from XSLT 1.0 spec:

A text node is never stripped unless it contains only whitespace characters.

So, for example, this:

<foo>
  <bar>   </bar>
</foo>

will be stripped down to:

<foo><bar/></foo>

because it had 3 whitespace-only text nodes (after <foo> and before <bar>, between <bar> and </bar>, and after </bar> and before </foo>).

Note also that because you have <xsl:output indent="yes"> in your stylesheet, it will end up being transformed to:

<foo>
   <bar/>
<foo>

in the output.

On the other hand, this:

<foo>
   text1
   <bar>  text2  </bar>
   text3
</foo>

Will not be stripped at all, because all text nodes it contains are not purely whitespace nodes.


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

...