How can I strip line breaks from my XML with XSLT?
I have this XSLT:
<xsl:strip-space elements="*" />
<xsl:template match="math">
<img class="math">
<xsl:attribute name="src">http://latex.codecogs.com/gif.latex?<xsl:value-of
select="text()" /></xsl:attribute>
</img>
</xsl:template>
Which is being applied to this XML (notice the line break):
<math>\text{average} = \alpha \times \text{data} + (1-\alpha) \times
\text{average}</math>
Unfortunately, the transform creates this:
<img
class="math"
src="http://latex.codecogs.com/gif.latex?\text{average} = \alpha \times \text{data} + (1-\alpha) \times 					\text{average}" />
Notice the whitesp开发者_Python百科ace character literals. Although it works, it's awfully messy. How can I prevent this?
It is not sufficient to use the normalize-space()
function as it is leaving mid-spaces!
Here is a simple and complete solution:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:strip-space elements="*" />
<xsl:template match="math">
<img class="math">
<xsl:attribute name="src">http://latex.codecogs.com/gif.latex?<xsl:value-of
select="translate(.,' 	 ', '')" /></xsl:attribute>
</img>
</xsl:template>
</xsl:stylesheet>
When this transformation is applied on the provided XML document:
<math>\text{average} = \alpha \times \text{data} + (1-\alpha) \times
\text{average}</math>
the wanted, correct result is produced:
<img class="math" src="http://latex.codecogs.com/gif.latex?\text{average}=\alpha\times\text{data}+(1-\alpha)\times\text{average}" />
Do note:
The use of the XPath 1.0
translate()
function to strip off all unwanted characters.There is no need to use the
replace()
function here -- it may not be possible to use it, because it is only available in XPath 2.0.
I am not sure how you are generating the text. But there are two ways:
You can use the xsl:strip-space element that is available in XSLT.
If you generate the text during XSLT process, then another way to achieve will be to make use of string process methods: normalize-space and replace methods.
The normalize-space function strips leading and trailing whitespace and replaces sequences of whitespace characters by a single space. With no parameters, it will operate on the string value of the context node.
<xsl:template match="math">
<img class="math">
<xsl:attribute name="src">http://latex.codecogs.com/gif.latex?<xsl:value-of select="normalize-space()" /></xsl:attribute>
</img>
</xsl:template>
Also your stylesheet can be simplified by using an attribute value template instead of xsl:attribute
.
<xsl:template match="math">
<img class="math" src="http://latex.codecogs.com/gif.latex?{normalize-space()}" />
</xsl:template>
精彩评论