How to use XQuery
to retrieve data from XML
XQuery is an Language that used to retrieve data from XML in
required format, XQuery uses FLWOR expressions (For, Let, Where, Order By,
Return), I am giving to some examples below to understand XQuery. By looking below example you should be able to retrieve data from XML using XQuery.
Create One XML file and save as “Employee.xml”
xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee
type=”Admin”>
<Name>Ritesh</Name>
<DOB>Jun-23-2000</DOB>
<DeptId>10</DeptId>
<Salary>2000</Salary>
</Employee>
<Employee
type=”Supervisor”>
<Name>Kumar</Name>
<DOB>Jan-20-2000</DOB>
<DeptId>20</DeptId>
<Salary>4000</Salary>
</Employee>
</Employees>
Example-1: To Find the Department Id of the employee name 'Ritesh'
for $emp in doc
(Employee.xml)/Employees/Employee
where $emp/Name =”Ritesh”
return $emp/DeptId
Return
Answer
<DeptId>10</DeptId>
If you want to
return only data then use below return statement
return data($emp/DeptId)
Return
Answer
10
If you want to
return Data in different Structure then use below return statement
return
<Id>{data($emp/DeptId)} </Id >
Return
Answer
<Id>10</Id>
Example-2: To Find the Employee whose salary is > 1000 and return name with
type
for $emp in doc("Employee.xml")/Employees/Employee
where $emp/Salary > 1000
order by $emp/Name
return
<Department>
<Department>
if ($emp/@type=”Admin”)
then
<Admin >data($emp/Name) </Admin >
else
<Supervisor>data($emp/Name) </Supervisor >
Return
Answer
<Department>
<Department>
<Admin>Kumar</Admin>
<Supervisor>Ritesh</Supervisor>
</Department>
</Department>
You can find more examples http://www.w3schools.com/xquery/default.asp
No comments:
Post a Comment