How can I break line breaks from my XML using 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> 

What applies to this XML (note line breaks):

 <math>\text{average} = \alpha \times \text{data} + (1-\alpha) \times \text{average}</math> 

Unfortunately, the conversion creates this:

 <img class="math" src="http://latex.codecogs.com/gif.latex?\text{average} = \alpha \times \text{data} + (1-\alpha) \times&#10;&#9;&#9;&#9;&#9;&#9;\text{average}" /> 

Pay attention to whitespace literals. Although it works, it is terribly dirty. How can I prevent this?

+4
source share
3 answers

Using the normalize-space() function is not enough, as it leaves the middle 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(.,' &#9;&#10;', '')" /></xsl:attribute> </img> </xsl:template> </xsl:stylesheet> 

When this conversion is applied to the provided XML document :

 <math>\text{average} = \alpha \times \text{data} + (1-\alpha) \times \text{average}</math> 

required, the correct result is obtained :

 <img class="math" src="http://latex.codecogs.com/gif.latex?\text{average}=\alpha\times\text{data}+(1-\alpha)\times\text{average}" /> 

Please note :

  • Use the XPath 1.0 translate() function to remove all unwanted characters.

  • There is no need to use replace() here - it may not be possible to use, because it is only available in XPath 2.0.

+4
source

I'm not sure how you generate text. But there are two ways:

+1
source

The normalize-space function separates leading and trailing spaces and replaces sequences of whitespace with one space. Without parameters, it will work with the string value of the node context.

 <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> 

You can also simplify your style by using the 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> 
+1
source

Source: https://habr.com/ru/post/1311944/


All Articles