Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip whitespace inside <xsl:attribute> tag?

Tags:

xml

xslt

In an XSLT stylesheet, how can I remove leading and trailing whitespace inside a <xsl:attribute> tag?

For example, the following stylesheet:

<xsl:template match="/">
  <xsl:element name="myelement">
    <xsl:attribute name="myattribute">
      attribute value
    </xsl:attribute>
  </xsl:element>
</xsl:template>

outputs:

<myelement myattribute="&#10;      attribute value&#10;    "/>

whilst I would like it to output:

<myelement myattribute="attribute value"/>

Is there any way to accomplish that other than collapsing the <xsl:attribute> start and end tags in a single line?

Because if the attribute value is not a plain line of text but the result of some complex calculation (for example using or tags), then collapsing all the code in one line to avoid the leading and trailing whitespace would result in a horribly ugly stylesheet.

like image 934
Theodore Lytras Avatar asked Sep 28 '13 21:09

Theodore Lytras


People also ask

How do you break a line in XSLT?

First of all, the &#xa (hex) or &#10 (dec) inside a <xsl:text/> will always work, but you may not see it. There is no newline in a HTML markup. Using a simple <br/> will do fine. Otherwise you'll see a white space.

What is the purpose of terminate attribute in xsl message tag?

The terminate attribute gives you the choice to either quit or continue the processing when an error occurs.

What does xsl value of select /> mean?

Definition and Usage The <xsl:value-of> element extracts the value of a selected node. The <xsl:value-of> element can be used to select the value of an XML element and add it to the output.


1 Answers

You could wrap the text by xsl:text or xsl:value-of:

<xsl:template match="/">
    <xsl:element name="myelement">
        <xsl:attribute name="myattribute">
            <xsl:text>attribute value</xsl:text>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

or

<xsl:template match="/">
    <xsl:element name="myelement">
        <xsl:attribute name="myattribute">
            <xsl:value-of select="'attribute value'"/>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

Is this useful for you? Otherwise please explain your problem in using a single line.

Please take notice of the comment of Michael Kay, it explains the problem to the point!

like image 78
Matthias M Avatar answered Nov 15 '22 05:11

Matthias M