Jump to content

XQuery/Tree View

From Wikibooks, open books for an open world

Motivation

[edit | edit source]

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

Method

[edit | edit source]

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 function

[edit | edit source]

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/(@*|*)))
     then 
     <table>
        {if (exists($element/text()))
         then <tr class="text">
                  <th></th>
                  <td>{$element/text()}</td>
              </tr>
         else ()
       }
       {for $attribute in $element/@*
       return
          <tr class="attribute">
             <th>@{name($attribute)}</th>
             <td>{string($attribute)}</td>
          </tr>
       }
       {for $node in $element/*
       return 
          <tr class="element">
             <th>{name($node)}</th> 
             <td>{local:element-to-nested-table($node)}</td>
          </tr>       
        }
    </table>
    else $element/text()
  };

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

Document display

[edit | edit source]

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
return
 <html>
    <head>
    <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}}
     </style>
    </head>
    <body>
    <h1>Tree view of {$uri} </h1>
     {local:element-to-nested-table($element)}
     </body>
 </html>

e.g.

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