Friday, June 12, 2015

XQuery Convert First Char of XML Element To Lower Case

Below is an XQuery that I have written for converting first character of XML element name from Upper Case to lower case

For Example

<Test>123</Test> will be converted to <test>123</test>

xquery version "1.0" encoding "Cp1252";
(:: pragma  parameter="$inputXml" type="xs:anyType" ::)
(:: pragma  type="xs:anyType" ::)

declare namespace xf = "http://www.tempuri.org/firstCharSmall/";

declare function xf:firstCharSmall($inputXml as element(*))
    as element(*) {
        (
element {concat(lower-case(substring(fn:local-name($inputXml),1,1)),substring(fn:local-name($inputXml),2))}
{
if(exists($inputXml/*)) then
(
xf:childTagHandler($inputXml)
)
else
(
data($inputXml)
)
}
        )
};

declare function xf:childTagHandler($node as node()*)
    as node()* {
        (
        for $counter in (1 to count($node/*))
        return
        (
element {concat(lower-case(substring(fn:local-name($node/*[$counter]),1,1)),substring(fn:local-name($node/*[$counter]),2))} 
        {
        (
        if (exists($node/*[$counter]/*[1]))
        then
        (
        xf:childTagHandler($node/*[$counter])
        )
        else 
        (
        data($node/*[$counter])
        )
        )
        }
        )  
)      
};

declare variable $inputXml as element(*) external;

xf:firstCharSmall($inputXml)


Hope it helps!