user2383177
user2383177

Reputation: 21

XSLT2.0 Uppercase first Letter of Regex Match

I have a a use case to convert camelCase elements in an xml document to NewCase as shown:

Current:

<firstName>John</firstName>
<lastName>Smith</lastName>
<userId>5692</userId>

Desired:

<FirstName>John</FirstName>
<LastName>Smith</LastName>
<UserId>5692</UserId>

I must facilitate this through XSLT. In order to do this, I identified a regex that would capture the camelCase for my requirement:

\b([a-z])([a-z]*[A-Z][a-z]*)\b

From there, I have been attempting to do this via XSLT2.0 by using the replace function:

 replace($xmlToParse,"\b([a-z])([a-z]*[A-Z][a-z]*)\b","REPLACED")

For the final block, I want to take the first segment of the matched regex (in lowerCase the segments would be 'l' and 'owercase' based on the above regex), and use the upper-case function to change that first segment/letter to upper case (so lowerCase would be LowerCase), and do this for every regex match in the XML. Unfortunately thus far I have been unable to achieve it.

Would anyone be able to give any insight on how to link it all together?

Upvotes: 2

Views: 933

Answers (1)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243479

This transformation:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

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

 <xsl:template match=
 "*[matches(name(), '[a-z]+[A-Z][a-z]*')]">
  <xsl:element name=
   "{upper-case(substring(name(),1,1))}{substring(name(),2)}">
   <xsl:apply-templates select="node()|@*"/>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML fragment (wrapped into a single top element to become a well-formed XML document):

<t>
    <firstName>John</firstName>
    <lastName>Smith</lastName>
    <userId>5692</userId>
</t>

produces the wanted, correct result:

<t>
      <FirstName>John</FirstName>
      <LastName>Smith</LastName>
      <UserId>5692</UserId>
</t>

Upvotes: 1

Related Questions