Welcome to our XQuery Updates tutorial! In this lesson, we'll learn how to update XML documents using XQuery, making your XML data more dynamic and versatile. Let's dive in!
XQuery Updates is an extension to the XQuery language that allows you to modify XML documents, not just query them. This is a powerful feature for managing and manipulating XML data in real-time applications.
The basic syntax for an XQuery Update consists of the let clause for defining variables and the for clause for iterating through elements. The delete, insert, and replace value of are the main functions used for updates.
xquery version "3.0";
let $doc := doc("example.xml")
let $element := $doc/element::element-name
for $item in $element
return
if ($item/attribute::attribute-name = "value") then
delete $item
else
...To delete an element, use the delete function inside the return clause.
xquery version "3.0";
let $doc := doc("example.xml")
let $element := $doc/element::element-name
for $item in $element
return
if ($item/attribute::attribute-name = "value") then
delete $item
else
()To insert an element, first define the new element and then use the insert function.
xquery version "3.0";
let $doc := doc("example.xml")
let $new-element := <new-element></new-element>
let $position := $doc/element::element-name[1]
return
$doc with $position[1]/following-sibling::* before $new-elementTo replace the value of an element, use the replace value of function.
xquery version "3.0";
let $doc := doc("example.xml")
let $element := $doc/element::element-name
return
$doc/element::element-name[1]/replace value of child::text() with "new-value"