Search code examples
xmlxsltxpathxslt-1.0xquery

How to handle the 'LOC_NAME' element value


In the below example we are trying to handle value of 'LOC_NAME' element, If 'Front' word are coming in the end then we are removing using xslt 1.0:

Can anyone help.

INPUT XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<LOC_NAME>Front</LOC_NAME>
<LOC_NAME>Arapaoa Front.</LOC_NAME>
<LOC_NAME>Arapaoa Island. Front</LOC_NAME>
<LOC_NAME>North Stake Front Stbd No.31</LOC_NAME>
<LOC_NAME>North Stake No.35</LOC_NAME>
</root>

EXPECTED OUTPUT:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<LOC_NAME>Front</LOC_NAME>
<LOC_NAME>Arapaoa</LOC_NAME>
<LOC_NAME>Arapaoa Island.</LOC_NAME>
<LOC_NAME>North Stake Front Stbd No.31</LOC_NAME>
<LOC_NAME>North Stake No.35</LOC_NAME>
</root>

XSLT CODE:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/root">
    <root>
        <xsl:apply-templates/>
    </root>
</xsl:template>

<xsl:template match="LOC_NAME">
<xsl:copy>
    <xsl:choose>
        <xsl:when test=".='Front'">
            <xsl:value-of select="'Front'"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="."/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:copy>    
</xsl:template>

</xsl:stylesheet>

Reference URL # http://xsltransform.net/6qCcddQ/1


Solution

  • The result you show could be achieved using:

    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:template match="/root">
        <root>
            <xsl:for-each select="LOC_NAME">
                <xsl:variable name="len" select="string-length(.)" />
                <xsl:copy>
                    <xsl:choose>
                        <xsl:when test="substring(., $len - 5)=' Front'">
                            <xsl:value-of select="substring(., 1, $len - 6)"/>
                        </xsl:when>
                        <xsl:when test="substring(., $len - 6)=' Front.'">
                            <xsl:value-of select="substring(., 1, $len - 7)"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:value-of select="."/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:copy>
            </xsl:for-each>
        </root>
    </xsl:template>
    
    </xsl:stylesheet>