XQuery Add
Adding and inserting data with XQuery
➕ What is XQuery Add?
XQuery Add operations allow you to insert new elements, attributes, and content into XML documents. You can create new XML structures or augment existing ones dynamically using XQuery expressions.
(: Adding new elements :)
<books>
{//book}
<book><title>New Book</title></book>
</books>
Adding Elements
XQuery provides multiple ways to add new elements to your XML output. You can construct new elements directly or combine existing data with new content.
Direct Constructor
Create elements with XML syntax
<item>New</item>
Computed Constructor
Build elements dynamically
element item {"New"}
Concatenation
Combine sequences
($seq1, $seq2)
Insert Expression
Add to existing nodes
insert node
🔹 Adding New Elements
Create and add new XML elements to your results:
<!-- Original XML -->
<library>
<book><title>Book 1</title></book>
</library>
(: Add a new book :)
<library>
{//book}
<book>
<title>Book 2</title>
<author>New Author</author>
</book>
</library>
Result:
<library>
<book><title>Book 1</title></book>
<book>
<title>Book 2</title>
<author>New Author</author>
</book>
</library>
🔹 Adding Attributes
Add attributes to elements dynamically:
(: Direct attribute :)
<book id="101" category="fiction">
<title>My Book</title>
</book>
(: Computed attribute :)
element book {
attribute id {"101"},
attribute category {"fiction"},
element title {"My Book"}
}
(: With variables :)
let $id := "101"
return <book id="{$id}"><title>My Book</title></book>
🔹 Adding Text Content
Insert text into elements:
(: Simple text :)
<message>Hello World</message>
(: With variables :)
let $name := "John"
return <greeting>Hello, {$name}!</greeting>
(: Concatenating text :)
let $first := "John"
let $last := "Doe"
return <name>{concat($first, " ", $last)}</name>
Result:
<greeting>Hello, John!</greeting>
<name>John Doe</name>
🔹 Adding Multiple Elements
Use FLWOR to add multiple elements:
(: Add elements for each item :)
<products>
{
for $i in (1 to 3)
return
<product>
<id>{$i}</id>
<name>Product {$i}</name>
</product>
}
</products>
Result:
<products>
<product>
<id>1</id>
<name>Product 1</name>
</product>
<product>
<id>2</id>
<name>Product 2</name>
</product>
<product>
<id>3</id>
<name>Product 3</name>
</product>
</products>
🔹 Combining Sequences
Merge existing and new data:
(: Combine two sequences :)
let $existing := //book
let $new :=
<book>
<title>New Title</title>
<price>25.99</price>
</book>
return ($existing, $new)
(: Add conditional elements :)
for $book in //book
return
<book>
{$book/*}
{if (not($book/isbn))
then <isbn>000-0-00-000000-0</isbn>
else ()}
</book>
🔹 Adding Nested Structures
Create complex nested XML:
(: Build nested structure :)
<catalog>
<category name="Fiction">
{
for $book in //book[@category="fiction"]
return
<item>
<title>{$book/title/text()}</title>
<details>
<author>{$book/author/text()}</author>
<price>{$book/@price}</price>
</details>
</item>
}
</category>
</catalog>