Changes

Jump to navigation Jump to search
89 bytes removed ,  18:38, 1 December 2023
m
Text replacement - "syntaxhighlight" to "pre"
This page contains code snippets that mainly originate from our [https://mailman.uni-konstanz.de/mailman/listinfo/basex-talk basex-talk] mailing list.
== If, then, else Compact Notations ==
<code>if</code>/<code>not</code>/<code>else</code> constructs can look pretty verbose in XQuery.
* The [[XQuery 3.0#Simple Map Operator|Simple Map Operator]] can be used to trigger an action if a value has a single item. The following two expressions are equivalent:
<pre classlang="brush:'xquery"'>
let $s := "X" return (
(: OLD :) if(count($s) = 1) then 'OK' else (),
* If you want to choose the first non-empty item from two arguments, we can use the position predicate:
<pre classlang="brush:'xquery"'>
let $s := "X" return (
(: OLD :) if(exists($s)) then $s else 'default',
== Computed Elements ==
Returns dynamically named elements:
<pre classlang="brush:'xquery"'>
let $root := "element"
let $value := "hi"
The result is an XML fragment with <code>&lt;element&gt;</code> as root node:
<pre classlang="brush:xml">
<element about="hi">
<foo>Bar!</foo>
This snippet transform a ''flat'' list of elements with <code>parentId</code>-references to a nested list.
<pre classlang="brush:'xquery"'>
declare function local:link($entries as node()*, $id as xs:string) {
let $entry := $entries[@id eq $id],
</pre>
results in
<pre classlang="brush:xml">
<entry id="entry1">
<entry id="entry2" parentId="entry1">
This snippet converts an IP address to its numeric representation:
<pre classlang="brush:'xquery"'>
let $ip := '134.34.226.65'
return fold-left(
tokenize($ip, '\.')!xs:integer(.), 0, function($n, $d) { 256 * $n + $d }, 0, map(xs:integer#1, tokenize($ip, '\.'))
)
</pre>
results in
<pre classlang="brush:xml">
2250433089
</pre>
== Count number of files ==
This snippets returns the number of JPG files in a directory and its sub-directoriessubdirectories:
<pre classlang="brush:'xquery"'>
basex "count(file:list('.',true(),'*.jpg'))"</pre>
The Linux equivalent is
<pre classlang="brush:xml">
find . | grep \.jpg$ | wc -l
</pre>
 
[[Category:XQuery]]
Bureaucrats, editor, reviewer, Administrators
13,554

edits

Navigation menu