Insert space between two elements

Here should go questions about transforming XML with XSLT and FOP.
eb621
Posts: 5
Joined: Tue Jul 31, 2012 1:32 pm

Insert space between two elements

Post by eb621 » Mon Apr 09, 2018 2:13 pm

Hi,

I have a stylesheet that just sorts out white-space in a document.Where there's any sort of white-space at the start of end of a text node it inserts a single space regardless of how much white-space there was originally. My problem is that if I just have white-space between two elements say -

Code: Select all


<root>
some text <abbrev>bob</abbrev> <emph>harry</emph>
</root>
I loose the space between bob and harry.

The part that sorts out the leading and trailing space is this -

Code: Select all


<xsl:template match="*[../text()[normalize-space(.) != '']]" mode="strip-and-inject">
<!--but this template matches any element appearing in mixed
content-->
<xsl:variable name="textbefore" select="preceding-sibling::node()[1][self::text()]"/>
<xsl:variable name="textafter" select="following-sibling::node()[1][self::text()]"/>
<!--Either of the preceding variables will be an empty node set if the
neighbor node is not text(), right?-->
<xsl:variable name="prevchar" select="substring($textbefore, string-length($textbefore))"/>
<xsl:variable name="nextchar" select="substring($textafter, 1, 1)"/>
<!--Now the action:-->
<xsl:if test="$prevchar != normalize-space($prevchar)">
<!--If the original text had a space before, add one back-->
<xsl:text> </xsl:text>
</xsl:if>
<xsl:copy>
<!--Copy the element over-->
<xsl:copy-of select="@*"/>
<xsl:apply-templates mode="#current"/>
</xsl:copy>
<xsl:if test="$nextchar != normalize-space($nextchar)">
<!--If the original text had a space after, add one back-->
<xsl:text> </xsl:text>
</xsl:if>
</xsl:template>
What can I do so that I retain the space between elements as per the above for nodes that also have text?

Many thanks

Radu
Posts: 6514
Joined: Fri Jul 09, 2004 5:18 pm

Re: Insert space between two elements

Post by Radu » Wed Apr 11, 2018 9:21 am

Hi,

Maybe you can check for this situation like:

Code: Select all

        <xsl:if test="$textbefore/preceding-sibling::node()[self::*]">
<!-- There is an element immediately before the text before -->
</xsl:if>
There is also a specialized XSLT users list where you can ask XSLT-related questions:

http://www.mulberrytech.com/xsl/xsl-list/#subscribing

Regards,
Radu
Radu Coravu
<oXygen/> XML Editor
http://www.oxygenxml.com

Post Reply