Tuesday, June 10, 2008

Querying contents of XML using XPATH

This can be used to query XML document and get value of particular node with iterating through all the nodes. It would be same as we use SQL query to get data from database.

public static void XpathQuery()
//XML document which contains data
string xmlDoc = "<?xml version='1.0'?>" +
"<Company>" +
"<Employee status='trainee'>Abhishek</Employee>" +
"<Employee status ='confirmed'>Vikram Pai</Employee>" +
"<Employee status ='confirmed'>Bhautik Shah</Employee>" +
"<Employee status ='confirmed'>Ashwini</Employee>" +
"<Employee status ='confirmed'>Dheeraj Pal</Employee>" +
"<Employee status ='confirmed'>Laxmi</Employee>" +

//Create object of reader using XmlTextReader
XmlTextReader reader = new XmlTextReader(xmlDoc, XmlNodeType.Element,null);

//Create object of XPathDocument using reader
XPathDocument xpathDoc = new XPathDocument(reader, XmlSpace.Preserve);

//Get navigator object from XPathDocument using CreateNavigator()
XPathNavigator navigator = xpathDoc.CreateNavigator( );

//prepare query
string query = "/Company/Employee[attribute::status='confirmed'][contains(text(),'Bhautik')]";

//get node iterator from query
XPathNodeIterator iterator = navigator.Select(query);

//display output
while(iterator.MoveNext( ))

// close reader.
reader.Close( );

The output will be:

Bhautik Shah

This is the output of query where we searched for employee with status equal to confirmed and value contains Bhautik. This way we can query XML document using XPATH.

No comments:

Post a Comment