Generating HTML from XML Data using XQuery: A Practical Guide

Learn how to transform XML data into HTML using XQuery. This tutorial demonstrates using XQuery expressions to select, format, and generate HTML output from XML data sources, providing a practical approach to creating dynamic web pages from XML-based data.



Generating HTML Output from XML Using XQuery

XQuery can be used to transform XML data into HTML. This is helpful for creating dynamic web pages from XML data sources. This involves using XQuery to select and format the relevant data from the XML file and then outputting it as HTML.

Example: Transforming XML Book Data to HTML

(Note: This example uses an XQuery expression and a Java program to process the data and generate the output. Screenshots from the original text are not included here. Please refer to the original document for visual verification of the example and its output. The descriptions below aim to convey the information present in those screenshots.)

`books.xml` (Example XML Data)


<bookstore>
  <book>
    <title>HTML is Fun</title>
    <author>Ajeet Kumar</author>
    <year>2012</year>
    <price>200.00</price>
  </book>
  <!-- More book elements -->
</bookstore>

`books.xqy` (XQuery Expression)


{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <p>{$x}</p>
}

This XQuery expression selects all `title` elements within the XML document, sorts them alphabetically, and wraps each title in a paragraph tag (`<p>`).

`XQueryTester.java` (Java Program)


import java.io.File;
import java.io.FileInputStream;
// ... (other imports) ...

public class XQueryTester {
    public static void main(String[] args) {
        // ... (code to execute the XQuery expression using SaxonXQDataSource) ...
    }
}

This Java program uses the Saxon library to execute the XQuery expression. This program would need to be compiled and run using a Java compiler (like `javac`) and Java Runtime Environment (JRE) respectively.

Test it Now

Extracting Only the Text Content

To get only the text content of the title elements, use the `data()` function within the XQuery expression.


{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return {data($x)}
}

Test it Now