Adding Elements and Text to XQuery Results: Integrating XML Data into HTML
Learn how to integrate XML data into HTML or other formats using XQuery's `data()` function. This tutorial demonstrates extracting string values from XML elements and attributes and using them to construct HTML fragments, enabling dynamic HTML generation from XML data sources.
Adding Elements and Text to XQuery Results
Understanding XQuery's `data()` Function
In XQuery, the `data()` function extracts the string value from an XML element or attribute. This is essential when you need to work with the textual content of XML elements or attributes. The `data()` function is often used in conjunction with other XQuery functions or expressions to manipulate or transform the content of XML documents. The `data()` function converts XML node to simple text.
Example: Adding HTML Elements and Text
This example shows how to add HTML elements and text to the output of an XQuery expression. It uses the `data()` function to extract data from the XML document and then constructs an HTML fragment including HTML elements around that data.
1. Sample XML Data (`books.xml`)
books.xml
<bookstore>
<book category="cooking">
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
</book>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
<!-- ... more books ... -->
</bookstore>
2. XQuery Expression (`books.xqy`)
XQuery Code
let $books := doc("books.xml")/bookstore/book
for $book in $books
order by $book/title
return <div>
<h3>{data($book/title)}</h3>
<p>Category: {data($book/@category)}</p>
</div>
This XQuery expression retrieves the book titles and their categories, wrapping each in a div element. The `data()` function extracts the string value from the XML elements and attributes. The result will be HTML that can be displayed directly in a web browser.
Conclusion
The `data()` function in XQuery is essential for integrating XML data into HTML or other formats. It allows you to extract the string values from XML elements and attributes to create the HTML or other markup you need.