Page 1 of 1

Add and Subtract to numerical suffix

Posted: Thu Jun 02, 2016 12:07 pm
by JackFrost
Any suggestion for an XSLT script where I can transfor this:

<a href="chapter-15.xhtml#b838"><span id="b235"/>


to this:

<a href="chapter-15.xhtml#b840"><span id="b232"/>


I just added 2 to the a href tag and subtracted 2 from the span id tag

Thanks in advance

Re: Add and Subtract to numerical suffix

Posted: Fri Jun 03, 2016 3:31 pm
by Radu
Hi,

The XSLT stylesheet would need to look something like this:

Code: Select all

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output method="xml" indent="no"/>
<!-- Match document -->

<xsl:template match="a[contains(@href, '#b')][span]" mode="copy">
<a>
<xsl:variable name="base" select="substring-before(@href, '#b')"/>
<xsl:variable name="numericAnchor" select="xs:integer(substring-after(@href, '#b')) + 2"/>
<xsl:attribute name="href">
<xsl:value-of select="concat($base, '#b', $numericAnchor)"/>
</xsl:attribute>
<xsl:apply-templates mode="copy"/>
</a>
</xsl:template>
<xsl:template match="span[starts-with(@id, 'b')][parent::a[contains(@href, '#b')]]" mode="copy">
<a>
<xsl:variable name="numericAnchor" select="xs:integer(substring-after(@id, 'b')) - 2"/>
<xsl:attribute name="href">
<xsl:value-of select="concat('b', $numericAnchor)"/>
</xsl:attribute>
<xsl:apply-templates mode="copy"/>
</a>
</xsl:template>

<xsl:template match="/">
<xsl:apply-templates mode="copy" select="."/>
</xsl:template>
<!-- Deep copy template -->
<xsl:template match="*|text()|@*" mode="copy">
<xsl:copy>
<xsl:apply-templates mode="copy" select="@*"/>
<xsl:apply-templates mode="copy"/>
</xsl:copy>
</xsl:template>
<!-- Handle default matching -->
<xsl:template match="*"/>
</xsl:stylesheet>
Ideally you should pose XSLT-related issues on the XSLT mailing list:

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

Regards,
Radu