XQuery/Tree View

< XQuery


You want a general purpose function that creates a tabular view of hierarchical data.


We will write a recursive function to display each node and then to display each child in an HTML table.

Some systems call this a "Grid View" of XML data.

element-to-nested-table functionEdit

The following function generates an HTML table with nested subtables for the child nodes.

declare function local:element-to-nested-table($element) {
   if (exists ($element/(@*|*)))
        {if (exists($element/text()))
         then <tr class="text">
         else ()
       {for $attribute in $element/@*
          <tr class="attribute">
       {for $node in $element/*
          <tr class="element">
    else $element/text()

Note that the rows displaying different kinds of items (text, attribute,element) are classed so that they may be styled.

Document displayEdit

This function can be used in a script to provide a viewer for any XML document.

declare namespace hc ="http://exist-db.org/xquery/httpclient";
declare option exist:serialize "method=xhtml media-type=text/html indent=yes";

 (: function declaration :)

let $uri := request:get-parameter("uri",())
let $element:= httpclient:get(xs:anyURI($uri),true(),())/hc:body/html
    <title>Tree view</title>
    <style type="text/css">
      th {{border-style:double}}
      tr {{border-style:dotted}}
      tr .attribute {{font-style:italic}}
      td {{border-style:ridge}}
    <h1>Tree view of {$uri} </h1>


  1. UWE's news feed
  2. Whisky data
  3. Employee data
  4. Met Office shipping Forecast mal-formed XML