How to add elements in XQuery Output

In this article we will discuss about how to add our own elements to the output of the XQuery.
  • 2236

We have seen that we can add the elements from the input document .i.e. any XML document in the output of the XQuery but if we want we can add our own elements in the output of the XQuery and this is the one of the most important feature of the XQuery. Look at the following XML File.

<?xml version="1.0" encoding="utf-8" ?>

<Inventory>

  <item category="mobile">

    <id>m01</id>

    <price>10000</price>

  </item>

  <item category="Television">

    <id>t01</id>

    <price>50000</price>

  </item>

  <item category="CDPlayer">

    <id>c01</id>

    <price>30000</price>

  </item>

</Inventory>

Now, we run the following XQuery against the above XML Document.

for $y in doc("Store.xml")/Inventory/item/id
order by $y
return $y

And the output will be as follows.

<id>m01</id>
<id>t01</id>
<id>c01</id>

Now, if we want we can add our own elements to the output of the XQuery and this will be as follows.

<html>
<h1>Inventory</h1>
<ol>
{
for $x in doc("Store.xml")/Inventory/item
order by $x/id
return <li>{data($x/id)}. Category: {data($x/@category)}</li>
}
</ol>
</html>

The above XQuery Expression will give the following output.

<html>
<h1>Inventory</h1>
<ol>
<li>c01.  Category: CDPlayer</li>
<li>m01. Category: mobile</li>
<li>t01.   Category: Television</li>
</ol>
</html>

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.