XQuery/Tree View
< XQuery
Motivation
editYou want a general purpose function that creates a tabular view of hierarchical data.
Method
editWe 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
editThe 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
editThis 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.
- UWE's news feed
- Whisky data
- Employee data
- Met Office shipping Forecast mal-formed XML