Skip to content

Instantly share code, notes, and snippets.

@derickson
Last active December 17, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derickson/5629858 to your computer and use it in GitHub Desktop.
Save derickson/5629858 to your computer and use it in GitHub Desktop.
Example of a simple XQuery recursive typeswitch for simple data conversion
xquery version "1.0-ml";
(:~
@author derickson
@date 2013-05-22
Example of a Recursive Typeswitch for simple data conversion
Works in MarkLogic Server 6+
:)
declare namespace a = "sample-ns-one";
declare namespace A = "sample-ns-two";
(:~
@param item -- thing to convert
@return converted thing
Converts data of format
<a:a key="whatever" changeMe="thing"><a:b>Whatever</a:b></a:a>
to
<A:A key="whatever" changed="thing"><A:B>Whatever</A:B></A:A>
:)
declare function local:convertOneToTwo( $item as element(a:a) ) as element(A:A) {
local:rts($item)
};
(:~
This is the recurisve typeswitch.
Notice how this function calls itself inside the typeswitch cases
@param nodes -- sequence of text() or element() nodes to be converted
@return converted nodes
:)
declare function local:rts( $nodes as node()*) as node()* {
for $node in $nodes
return
typeswitch ($node)
case text() return
$node
case attribute(changeMe) return
attribute changed {fn:data($node)}
case attribute() return
$node
case element(a:a) return
element A:A {
local:rts(($node/@*, $node/node()))
}
case element(a:b) return
element A:B {
local:rts(($node/@*, $node/node()))
}
default return
fn:error(xs:QName("ERROR"), "unmapped: " || xdmp:describe($node))
};
local:convertOneToTwo( <a:a key="whatever" changeMe="thing"><a:b>Whatever</a:b></a:a> )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment