Shanmugalakshmi
Shanmugalakshmi

Reputation: 267

How to retain space in XSL

I have an XML of the following process

<p>
  <author>
    <surname>John</surname> <given-name>Chen</given-name>
    <surname>Ram</surname> <given-name>Chen</given-name> 
    <surname>Raja</surname> <given-name>Singh</given-name> 
  </author>
</p>

Major problem is in space only. Space between surname and given-name, but after converting the file, space is gone. But I need retain space.

<p>
  <span class="author">
    <span class="surname">John</span> <span class="given-name">Chen</span>
    <span class="surname">Ram</span> <span class="given-name">Chen</span>
    <span class="surname">Raja</span> <span class="given-name">Singh</span>
  </span>
</p>

Thanks for advance.

XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="p span" />
<xsl:preserve-space elements="p span" />
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="p">
        <xsl:element name="p"><xsl:apply-templates/></xsl:element>
    </xsl:template>
    <xsl:template match="author|surname|given-name">
        <xsl:element name="span">
            <xsl:attribute name="class"><xsl:value-of select="name()"/></xsl:attribute>
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 0

Views: 694

Answers (1)

Resu
Resu

Reputation: 64

Will be better if you insert space in stylesheet

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:strip-space elements="author"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="p">
    <xsl:element name="p"><xsl:apply-templates/></xsl:element>
</xsl:template>
<xsl:template match="author|surname|given-name">
    <xsl:element name="span">
        <xsl:attribute name="class">
            <xsl:value-of select="name()"/>
        </xsl:attribute>
        <xsl:apply-templates/>
    </xsl:element>
    <xsl:text>&#x20;</xsl:text>
</xsl:template>
</xsl:stylesheet>

First, strip all spaces inside author element <xsl:strip-space elements="author"/> for avoid duplication.

Second, insert single space <xsl:text>&#x20;</xsl:text> between <span class="surname"> and <span class="given-name">.

Upvotes: 1

Related Questions