<!-- Taking the same approach as Scala we return options which are either none or some -->
<option>
<none/>
</option>
<option>
<some>4</some>
</option>
<!-- Example of a lookup map represented in XML -->
<map>
<entry key="PH3330L">SOT669</entry>
<entry key="BUK100-50GL">SOT78B</entry>
<entry key="PSMN003-30B">SOT404</entry>
</map>
An example of how you could model options in XQuery and build some utility functions to make your code more safe.
declare function local:getOrElse($map as element(map), $key as xs:string, $else) {
let $option := local:get($map, $key)
return (if (empty($option/some)) then $else else data($option/some))
};
declare function local:get($map as element(map), $key as xs:string) as element(option) {
(if (empty($map/entry[@key=$key])) then <option><none/></option> else <option><some>{data($map/entry[@key=$key])}</some></option>)
};
let $map1 :=
<map>
<entry key="PH3330L">SOT669</entry>
<entry key="BUK100-50GL">SOT78B</entry>
<entry key="PSMN003-30B">SOT404</entry>
</map>
let $map2 :=
<map>
<entry key="robby">1977</entry>
<entry key="ivan">1987</entry>
</map>
return
<lookups>
<package>{local:getOrElse($map1, "PH3330L", "test1")}</package>
<package>{local:getOrElse($map1, "INVALID", "test1")}</package>
<age>{2012 - local:getOrElse($map2, "robby", 0)}</age>
<age>{2012 - local:getOrElse($map2, "amanda", 2012)}</age>
</lookups>
The result looks like this if you test it on e.g. Zorba.
<lookups> <package>SOT669</package> <package>test1</package> <age>35</age> <age>0</age> </lookups>
No comments:
Post a Comment