Have a requirement to create slugs from XML content.
I was navigating to create Slugs from Titles and found the below ones listed.
- Creating Slugs from Titles?
- Java code/library for generating slugs (for use in pretty URLs)
- and similar others.
I was looking for perfect solution for an XSL solution, which provides better slugifies like a PHP solution: http://blog.tersmitten.nl/slugify and also takes care of duplicates in the file system.
Input XML
<table>
    <tr>
        <td>2D</td>
        <td>Two Dimension</td>
    </tr>
    <tr>
        <td>A/C</td>
        <td>Account</td>
    </tr>
    <tr>
        <td>A/C</td>
        <td>Air Condition</td>
    </tr>
    <tr>
        <td>L&T</td>
        <td>Larsen & Toubro</td>
    </tr>
    <tr>
        <td>M + [ # ]</td>
        <td>Modified Algo</td>
    </tr>
</table>
Expected Output
file: 2d.txt
------------
2D
Two Dimension
file: a-c.txt
-------------
A/C
Account
file: a-c-2.txt
---------------
A/C
Air Condition
file: l-t.txt
-------------
L&T
Larsen & Turbo
file: m.txt (NOT m-.txt)
-------------
M + [ # ]
Modified Algo
Tried XSL
<?xml version="1.0"?>
<xsl:stylesheet extension-element-prefixes="redirect" version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:redirect="http://xml.apache.org/xalan/redirect">
    <xsl:output method="text" version="1.0" />
    <xsl:template match="/">
        <xsl:for-each select="table/tr">
            <!-- The logic for variable value requires attention!! -->
            <xsl:variable name="acronym" select="translate(td[1], 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')" />
            <xsl:variable name="tmpFilename" select="concat('C:/Temp/', $acronym, '.txt')" />
            <xsl:variable name="filename">
                <xsl:choose>
                    <xsl:when test="document($tmpFilename)">
                        <!-- Require logic to handle duplicate file existence. -->
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:value-of select="$filename" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:variable>
            <redirect:write select="$filename">
                <xsl:value-of select="td[1]" />
                <xsl:text>
</xsl:text>
                <xsl:value-of select="td[2]" />
            </redirect:write>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
Note: The file name should include only the OS supported characters. The rest should be converted to '-'. Also, there shouldn't be leading and trailing '-' characters (e.g. the last output file as mentioned above).
 
     
    