XQuery

XQuery

(pwalmsley@datypic.com)

ISBN: 1491915103

2nd edition, , O'Reilly Media, Inc.

Appendix A: Built-in Function Reference

Please note that the book contains many inline examples and informal tables that are not provided here.

Example A-1. Using xml:base (http://datypic.com/input/cats.xml)
<catalogs>
  <catalog name="ACC" xml:base="http://datypic.com/ACC/">
    <product number="443" href="prod443.html"/>
    <product number="563" href="prod563.html"/>
  </catalog>
  <catalog name="WMN" xml:base="http://datypic.com/WMN/">
    <product number="557" href="prod557.html"/>
  </catalog>
</catalogs>
Table A-3. Examples of the data function on untyped nodes
ExampleReturn valueReturn type
data($cat//product[1]/number) 557 xs:untypedAtomic
data($cat//number) (557, 563, 443, 784) xs:untypedAtomic*
data($cat//product[1]/@dept) WMN xs:untypedAtomic
data($cat//product[1]/colorChoices) navy black xs:untypedAtomic
data($cat//product[1]) 557 Fleece Pullover navy black xs:untypedAtomic
data($cat//product[4]/desc) Our favorite shirt! xs:untypedAtomic
Table A-4. Examples of the data function on typed nodes
ExampleReturn valueReturn type
data($cat//product[1]/number) 557 xs:integer
data($cat//number) (557, 563, 443, 784) xs:integer*
data($cat//product[1]/@dept) WMN xs:string
data($cat//product[1]/colorChoices) (navy, black) xs:string*
data($cat//product[1]) Error FOTY0012 N/A
data($cat//product[4]/desc) Our favorite shirt! xs:untypedAtomic
Table A-5. Examples of the data function on non-nodes
ExampleReturn valueReturn type
data(1) 1 xs:integer
data( (1, 2, 3) ) (1, 2, 3) xs:integer*
data( [1, 2, 3] ) (1, 2, 3) xs:integer*
data( [1, 2, ['a', 'b', 'c']] ) (1, 2, 'a', 'b', 'c') xs:anyAtomicType*
data( () ) ()
data( concat#3 ) Error FOTY0013
Example A-2. Product catalog document with IDs (catalog-with-ids.xml)
<catalog>
  <product dept="WMN">
    <id>A1</id>
    <number>557</number>
    <name language="en">Fleece Pullover</name>
  </product>
  <product dept="ACC">
    <id>A2</id>
    <number>563</number>
    <name language="en">Floppy Sun Hat</name>
  </product>
</catalog>
Example A-3. Using generate-id
Query
<html>
  <body>
    <h1>Table of Contents</h1>
    {for $prod in doc("catalog.xml")//product
     return <p><a href="#{generate-id($prod)}">{data($prod/number)}</a></p>}
  
    <h1>Product Info</h1>
    {for $prod in doc("catalog.xml")//product
     return 
      (<h2 id="{generate-id($prod)}">{data($prod/number)}</h2>,
       <p>Name: {data($prod/name)}, Dep: {data($prod/@dept)}</p>)}
  </body>
</html>
Results
<html>
   <body>
     <h1>Table of Contents</h1>
     <p><a href="#d0e3">557</a></p>
     <p><a href="#d0e15">563</a></p>
     <p><a href="#d0e24">443</a></p>
     <p><a href="#d0e33">784</a></p>
     <h1>Product Info</h1>
     <h2 id="d0e3">557</h2>
     <p>Name: Fleece Pullover, Dep: WMN</p>
     <h2 id="d0e15">563</h2>
     <p>Name: Floppy Sun Hat, Dep: ACC</p>
     <h2 id="d0e24">443</h2>
     <p>Name: Deluxe Travel Bag, Dep: ACC</p>
     <h2 id="d0e33">784</h2>
     <p>Name: Cotton Dress Shirt, Dep: MEN</p>
   </body>
</html>
Example A-4. XML document with IDs and IDREFs (book.xml)
<book>
  <section id="preface">This book introduces XQuery...
    The examples are downloadable<fnref ref="fn1"/>...
  </section>
  <section id="context">...</section>
  <section id="language">...Expressions, introduced
   in <secRef refs="context"/>, are...
  </section>
  <section id="types">...As described in
    <secRef refs="context language"/>, you can...
  </section>
  <fn fnid="fn1">See http://datypic.com.</fn>
</book>
Example A-5. A simple call to json-to-xml
Query
xquery version "3.1";
json-to-xml('{
   "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null
}')
Results
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <number key="number">557</number>
  <string key="name">Fleece Pullover</string>
  <array key="colorChoices">
    <string>navy</string>
    <string>black</string>
  </array>
  <boolean key="is-current">true</boolean>
  <null key="other"/>
</map>
Example A-6. Calling json-to-xml with options
Query
xquery version "3.1";
json-to-xml('{
   "number": 557,
   "name": "Fleece Pullover",
   "name": "Fleece Pullover Redux",
   "colorChoices": ["navy \u00E9", "black \uFFFF"],
   "is-current": true,
   "other": null
}',
map {"duplicates": "use-first",
  "liberal": false(),
  "validate": false(),
  "escape": false(),
  "fallback": function($s){"ERROR!!"}})
Results
<map xmlns="http://www.w3.org/2005/xpath-functions">
  <number key="number">557</number>
  <string key="name">Fleece Pullover</string>
  <array key="colorChoices">
    <string>navy é</string>
    <string>black ERROR!!</string>
  </array>
  <boolean key="is-current">true</boolean>
  <null key="other"/>
</map>
Example A-7. Document with xml:lang attributes specified (descs.xml)
<desclist xml:lang="en">
  <desc xml:lang="en-US">
    <line>The first line of the description.</line>
  </desc>
  <desc xml:lang="fr">
    <line>La premi&#232;re ligne de la déscription.</line>
  </desc>
</desclist>
Example A-8. Example of the last function
Query
let $catalog := doc("catalog.xml")/catalog
for $prod in $catalog/product
return concat($prod/number,
            (if ($prod is $catalog/product[last()]) then (".") else (", ")) )
Results

      
Example A-9. A library module (strings.xqm)
module namespace strings = "http://datypic.com/strings";
declare variable $strings:maxStringLength := 32;
declare function strings:trim($arg as xs:string?) as xs:string? {
  replace(replace($arg,'^\s+',''),'\s+$','')
};
Example A-10. A simple call to load-xquery-module
Query
xquery version "3.1";
declare namespace strings = "http://datypic.com/strings";
let $library := load-xquery-module("http://datypic.com/strings")
let $trimFunction := $library?functions?(xs:QName("strings:trim"))?1
return $trimFunction("   x   y   ")
Equivalent value of $library
map {
  "variables": map{
                 xs:QName("strings:maxStringLength"): 32
                },
  "functions": map{
                 xs:QName("strings:trim"): map{
                     1: strings:trim#1 
                   }
                }
}
Results

      
Example A-11. Library module that is dynamically loaded (lib2.xqm)
xquery version "3.1";
module namespace prod = "http://datypic.com/prod";
declare context item as element(catalog) external;
declare variable $prod:label as xs:string external;
declare variable $prod:prods as element(product)* := product;
declare function prod:countProds ($prods as element(product)*) as xs:string
  {concat($prod:label, ': ', count($prods))};
declare function prod:countProds ($prods as element(product)*, 
                                  $dept as xs:string) as xs:string
  {concat($prod:label, ': ', count($prods[@dept = $dept]))};
Example A-12. A more complex call to load-xquery-module
Query
xquery version "3.1";
declare namespace prod = "http://datypic.com/prod";
let $library := 
  load-xquery-module("http://datypic.com/prod",
                     map {"context-item": doc("catalog.xml")/catalog,
                          "location-hints": "lib2.xqm",
                          "variables": map{
                            xs:QName("prod:label") : "Product Count"}
                     })
let $prodsVariableValue := $library?variables?(xs:QName("prod:prods"))
let $countProdArity1 := $library?functions?(xs:QName("prod:countProds"))?1
return $countProdArity1($prodsVariableValue)
Equivalent value of $library
map {
  "variables": map{
                 xs:QName("prod:label"): "Product Count",
                 xs:QName("prod:prods"): doc("catalog.xml")/catalog/product
                },
  "functions": map{xs:QName("prod:countProds"): map{
                     1: prod:countProds#1,
                     2: prod:countProds#2 
                    }
                }
}
Results

      
Example A-13. XML document with namespaces (names.xml)
<noNamespace>
  <pre:prefixed xmlns="http://datypic.com/unpre"
                xmlns:pre="http://datypic.com/pre">
    <unprefixed pre:prefAttr="a" noNSAttr="b">123</unprefixed>
  </pre:prefixed>
</noNamespace>
Example A-14. Nilled elements (nils.xml)
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <child>12</child>
  <child xsi:nil="true"></child>
  <child></child>
  <child/>
  <child xsi:nil="false"></child>
</root>
Example A-15. A simple call to parse-json
Query
xquery version "3.1";
parse-json('{
   "number": 557,
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true,
   "other": null 
}')
Results
map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": () 
}
Example A-16. Calling parse-json with options
Query
xquery version "3.1";
parse-json('{
   "number": 557,
   "name": "Fleece Pullover",
   "name": "Fleece Pullover Redux",
   "colorChoices": ["navy \u00E9", "black \uFFFF"],
   "is-current": true,
   "other": null
}',
map {"duplicates": "use-first",
  "liberal": false(),
  "validate": false(),
  "escape": false(),
  "fallback": function($s){"ERROR!!"}
})
Results
map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy é", "black ERROR!!"],
   "is-current": true(),
   "other": () 
}
Example A-17. Serializing JSON to a string
Query
xquery version "3.1";
serialize(map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": () 
},
<output:serialization-parameters
   xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
  <output:method value="json"/>
  <output:indent value="yes"/>
</output:serialization-parameters>)
Results

      
Example A-18. Expressing serialization parameters as a map
<xquery version "3.1";
serialize(map {
   "number": xs:double(557),
   "name": "Fleece Pullover",
   "colorChoices": ["navy", "black"],
   "is-current": true(),
   "other": () 
}, map {
   "method": "json",
   "indent"> true()
})
Example A-19. Calling the transform function (formerly Example A-18 in first release)
Query
xquery version "3.1";
let $result := transform(
  map {
    "stylesheet-location": "render.xsl",
    "source-node": doc("catalog.xml")
  })
return $result?output
Contents of render.xsl
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="catalog">
    <p>There are <xsl:value-of select="count(product)"/> products.</p>
  </xsl:template>
</xsl:stylesheet>
Results
<p>There are 4 products.</p>
Example A-20. Calling the transform function with stylesheet parameters (formerly Example A-19 in first release)
Query
xquery version "3.1";
let $result := transform(
  map {
    "stylesheet-location": "render2.xsl",
    "source-node": doc("catalog.xml"),
    "stylesheet-params": map { QName("", "label"): "Note",
                               QName("", "msg"): "Hi!"}
  })
return $result?output
Contents of render2.xsl
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="label"/>              
  <xsl:param name="msg"/>              
  <xsl:template match="catalog">
    <p>
      <xsl:value-of select="$label"/>
      <xsl:text>: </xsl:text>
      <xsl:value-of select="$msg"/>
      <xsl:text>. There are </xsl:text>
      <xsl:value-of select="count(product)"/>
      <xsl:text> products.</xsl:text>
    </p>
  </xsl:template>
</xsl:stylesheet>
Results
<p>Note: Hi! There are 4 products.</p>
Datypic XQuery Services