Scott Hanselman

Alphabetizing your .NET Resource (RESX) files

April 09, 2005 Comment on this post [1] Posted in ASP.NET | Corillian | PDC | XML | Tools
Sponsored By

We internationalize all our ASP.NET Web Applications, and usually end up with hundreds, if not thousands of strings in our RESX files. The names are all very hierarchical, like "AccountSummary.DataGrid.Columns.AvailableBalance" so you can see why it's important to keep them alphabetized. Additionally, there are usually a dozen or more of these RESX files in multiple levels of directories.

So, a little snazzy batch file action:

for /f "Tokens=*" %%i in ('dir /b /s *.resx') do nxslt "%%i"  alpharesx.xslt -o temp.xml & copy temp.xml "%%i" /y

The "dir /b /s" is "Directory BARE FORMAT FULL PATH all SUBDIRECTORIES" which provides the iterator for the FOR DO batch file loop. I had to use a temp.xml file because the nxslt tool didn't allow me to use the same filename for the input and output.

"nxslt" is a fantastic command-line .NET XSLT front end by Oleg Tkachenko. There are many command-line XSLT tools out there, but Oleg's is by far the most powerful and flexible.

The alpharesx.xslt is this XSLT stylesheet. It copies (xsl:copy-of) the RESX header stuff, then sorts the data nodes by name. There's no doubt even 'terser' XSLT-y ways to do this, but this is a start. Thanks to Travis Illig for the idea and starting chunk of XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="/" xml:space="preserve">
        <root>
            <xsl:copy-of select="root/xsd:schema"/>
            <xsl:copy-of select="root/resheader"/>
            <xsl:apply-templates select="root/data">
                <xsl:sort select="@name" />
            </xsl:apply-templates>
        </root>
    </xsl:template>
   
    <xsl:template match="data" xml:space="preserve">
        <data><xsl:attribute name="name"><xsl:value-of select="@name" /></xsl:attribute>
            <value><xsl:value-of select="value" /></value>
        </data>
    </xsl:template>
</xsl:stylesheet>

I'm also sure there's all sorts of SED-style ways to accomplish this, but this solution seem to be the simplest solution for this, short of writing a little custom C# program. It also was a faster-to-write solution than a new program.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
April 10, 2005 17:47
Hey, thanks for the plug! I'm glad you found nxslt useful.

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.