Cover Image for XQuery First Example
107 views

XQuery First Example

Sure! Let’s start with a simple XQuery example to get you started. In this example, we’ll write an XQuery to extract information from an XML document and return specific data. We’ll use a basic XML document representing a list of books as our data source.

XML Document (books.xml):

<books>
  <book>
    <title>XQuery 101</title>
    <author>John Doe</author>
    <price>25.00</price>
  </book>
  <book>
    <title>XML Fundamentals</title>
    <author>Jane Smith</author>
    <price>30.00</price>
  </book>
</books>

Now, let’s write an XQuery to extract the titles of all the books:

XQuery:

for $book in doc("books.xml")//book
return $book/title

Output:

<title>XQuery 101</title>
<title>XML Fundamentals</title>

Explanation:

  1. The XQuery starts with a “for” clause that iterates over each <book> element in the XML document. The doc("books.xml") function is used to load the XML document into the query.
  2. The “return” clause specifies what should be returned for each iteration. In this case, we are returning the <title> element for each <book> element selected in the “for” clause.

This XQuery example retrieves the titles of all the books from the XML document and returns them as a sequence of <title> elements.

Remember to ensure that you have an XML file named “books.xml” containing the provided XML data when running this XQuery example. You can use an XQuery processor or editor to execute the XQuery and see the results.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS