How to perform operation on node using XQuery function in XML?Explain with an example ?

 Posted by Bharathi Cherukuri on 5/11/2012 | Category: Web Services, Remoting Interview questions | Views: 2081 | Points: 40
Answer:

To explain given problem, first we will see an example in XML.

Example:


Save the given XML file with "bookmart.xml"

<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="CHILDREN">
<title lang="en">Jungle Book</title>
<author>Rudyard Kipling</author>
<year>1894</year>
<price>99.89</price>
</book>
<book category="ADVENTURE">
<title lang="en">The Book of the Thousand Nights and a Night </title>
<author>Sir Richard Francis Burton</author>
<year>1885-88</year>
<price>149.99</price>
</book>
<book category="WEB PROGRAMING">
<title lang="en">XPath and XPointer</title>
<author>John E. Simpson</author>
<year>2002</year>
<price>299.99</price>
</book>
<book category="WEB PROGRAMING">
<title lang="en">XML Programing</title>
<author>R.Allen Wype</author>
<author>Sultan Rehman</author>
<author>Brad Leupen</author>
<year>2002</year>
<price>229.95</price>
</book>
</bookstore>


Now, here is a way to perform operations on node with XQuery.

1. XQuery uses doc() function to retrieve data from XML document.
If you want to select all title elements of "bookmart.xml" , then you should write as follows:

doc("bookmart.xml")/bookstore/book/title


When this XQuery run than it will get like that,


<title lang="en">Jungle Book</title>
<title lang="en">The Book of the Thousand Nights and a Night</title>
<title lang="en">XPath and XPointer</title>
<title lang="en">XML Programing</title>


2. Using XQuery we can predicate the limit of an exiracted data from XML documents.
Now, We write a predicate for XQuery in which we got all book elements whose price has less than 150.

doc("books.xml")/bookstore/book[price<150]


Result will be as follows:


<book category="CHILDREN">
<title lang="en">Jungle Book</title>
<author>Rudyard Kipling</author>
<year>1894</year>
<price>99.89</price>
</book>
<book category="ADVENTURE">
<title lang="en">The Book of the Thousand Nights and a Night </title>
<author>Sir Richard Francis Burton</author>
<year>1885-88</year>
<price>149.99</price>
</book>


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response