0

Input xml code:

<Job>
<Telephone> 123/ 345-566 | 456-394-798 | (234)-453-245 </Telephone>
</Job>

Output xml code:

<Job>
<PhoneAreaCode> 123|456|234 </PhoneAreaCode>
</Job>

I have written an xslt 2.0 file using the replace() function with regex to achieve my output xml. But my VisualStudio supports only xslt 1.0.

Can you please assist me in writing an xslt code for the Output xml code.

Note: I need to store 123|456|234 in a global variable so that I can use it in various occurances in my output xml file.

Thanks!, In advance.

  • For an alternative to `replace()` see: https://stackoverflow.com/a/30339654/3016153 However, there is no regex support in XSLT 1.0 - and I am not sure what logic needs to applied here to get the shown result (it looks like you need to tokenize first). – michael.hor257k Nov 04 '18 at 08:24
  • How long are you prepared to put up with the limitations of a 20-year old version of XSLT, given that more up-to-date versions are available from other suppliers? (And it's not just you that's having to put up with it. You're asking the community to help you get around its limitations.) – Michael Kay Nov 04 '18 at 09:13

1 Answers1

0

A single example is often not enough to reliably deduce the logic that needs to be applied in order to handle all possible scenarios.

Looking at the example you provided, it seems to me that the real problem here is not how to replace(), but how to tokenize().

Consider the following stylesheet:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Telephone">
    <PhoneAreaCode>
        <xsl:call-template name="tokenize-and-extract">
            <xsl:with-param name="text" select="."/>
        </xsl:call-template>
    </PhoneAreaCode>
</xsl:template>

<xsl:template name="tokenize-and-extract">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="'|'"/>
        <xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
        <xsl:if test="$token">
            <xsl:value-of select="substring(translate($token, ' /()-', ''), 1, 3)"/>
        </xsl:if>
        <xsl:if test="contains($text, $delimiter)">
            <!-- recursive call -->
            <xsl:text>|</xsl:text>
            <xsl:call-template name="tokenize-and-extract">
                <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
            </xsl:call-template>
        </xsl:if>
</xsl:template>

</xsl:stylesheet>

Applied to your example input XML, the result will be:

<Job>
  <PhoneAreaCode>123|456|234</PhoneAreaCode>
</Job>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51