XQuery
Priscilla Walmsley (pwalmsley@datypic.com)
ISBN: 1491915103
2nd edition, , O'Reilly Media, Inc.
Chapter 8: Functions
Please note that the book contains many inline examples and informal tables that are not provided here.
declare function local:discountPrice( $price as xs:decimal?, $discount as xs:decimal?, $maxDiscountPct as xs:integer?) as xs:decimal? { let $maxDiscount := ($price * $maxDiscountPct) div 100 let $actualDiscount := min( ($maxDiscount, $discount) ) return ($price - $actualDiscount) }; let $prod := doc("prices.xml")//prod[1] return local:discountPrice($prod/price, $prod/discount, 15)
declare function local:discountPrice( $price as xs:decimal?, $discount as xs:decimal?, $maxDiscountPct as xs:integer?) as xs:double? { let $newDiscount := if ($discount) then $discount else 0 let $maxDiscount := if ($maxDiscountPct) then ($price * $maxDiscountPct) div 100 else 0 let $actualDiscount := min( ($maxDiscount, $newDiscount) ) return ($price - $actualDiscount) }; let $prod := doc("prices.xml")//prod[1] return local:discountPrice($prod/price, $prod/discount, 15)
declare function local:prod2ndDigit() as xs:string? { substring(number, 2, 1) }; doc("catalog.xml")//product[local:prod2ndDigit() > '5']
declare function local:prod2ndDigit($prod as element()?) as xs:string? { substring($prod/number, 2, 1) }; doc("catalog.xml")//product[local:prod2ndDigit(.) > '5']
declare function local:num-descendant-elements ($el as element()) as xs:integer { sum(for $child in $el/* return local:num-descendant-elements($child) + 1) };