joewiz
7/28/2016 - 6:44 PM

Find differences between two strings, with XQuery

Find differences between two strings, with XQuery

<differences>
    <difference position="7">
        <string1 codepoint="68">D</string1>
        <string2 codepoint="100">d</string2>
    </difference>
    <difference position="17">
        <string1 codepoint="233">é</string1>
        <string2 codepoint="101">e</string2>
    </difference>
</differences>
xquery version "3.1";

declare function local:find-differences($string1 as xs:string, $string2 as xs:string) {
    <differences>{
        if ($string1 = $string2) then 
            ()
        else
            let $codepoints1 := string-to-codepoints($string1)
            let $codepoints2 := string-to-codepoints($string2)
            for $codepoint1 at $n in $codepoints1
            let $codepoint2 := $codepoints2[$n]
            return
                if ($codepoint1 = $codepoint2) then 
                    () 
                else 
                    <difference position="{$n}">
                        <string1 codepoint="{$codepoint1}">{codepoints-to-string($codepoint1)}</string1>
                        <string2 codepoint="{$codepoint2}">{codepoints-to-string($codepoint2)}</string2>
                    </difference>
    }</differences>
};

let $name1 := "Nieto Del Río, Félix"
let $name2 := "Nieto del Río, Felix"
return 
    local:find-differences($name1, $name2)