Search code examples
xmlxsltcamelcasing

How would you use XSL to transform all elements and all attributes from PascalCase to camelCase?


I would like to transform ALL/ANY elements and attributes (not just the explicit elements/attributes in my small sample below) in my XML file from PascalCase to camelCase.

Does anyone have an XSL transform that can do this?

This:

<?xml version="1.0" encoding="utf-8" ?>
<Config Version="2" Name="Test">
    <Process Name="Main">
        X
    </Process>
</Config>

Should become this:

<?xml version="1.0" encoding="utf-8" ?>
<config version="2" name="Test">
    <process name="Main">
        X
    </process>
</config>

Solution

  • Try this:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
    >
      <xsl:output method="xml" indent="yes"/>
    
      <!-- everything not mentioned below (e.g. text, comments, processing instructions) -->
      <xsl:template match="node()">
        <xsl:value-of select="."/>
      </xsl:template>
    
      <!-- attributes -->
      <xsl:template match="@*">
        <xsl:attribute name="{concat(translate(substring(local-name(), 1, 1),'QWERTYUIOPASDFGHJKLZXCVBNM','qwertyuiopasdfghjklzxcvbnm'), substring(local-name(), 2))}">
          <xsl:value-of select="."/>
        </xsl:attribute>
      </xsl:template>
    
      <!-- elements -->
      <xsl:template match="*">
        <xsl:element name="{concat(translate(substring(local-name(), 1, 1),'QWERTYUIOPASDFGHJKLZXCVBNM','qwertyuiopasdfghjklzxcvbnm'), substring(local-name(), 2))}">
          <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
      </xsl:template>
    
    
    </xsl:stylesheet>
    

    NB: if using XSLT 2 you could replace the translate function with the lower-case function.