Thursday, August 23, 2007

XML & XPath Expression

When we have an application which is having XML Files as the data storage and need the fastest way to only read the data, XPath will be a good solution.

How to loop the data from an xml into XPath is quite simple.
I will be using .Net code below to do this.

XPathDocument xpDoc = new XPathDocument(@"C:\Temp\data.xml");
XPathNavigator xpNav = xpDoc.CreateNavigator();
XPathNodeIterator xpIter = xpNav.Select("/root/row");
while (xpIter.MoveNext())
{
Console.WriteLine(xpIter.Current.GetAttribute("id", string.Empty));
}


The code will simply load the data.xml and then loop the data and write the ID to the console.

There will be occasions where we need to perform more complex queries to the data which we can do it quite simple such as in the SQL statement below:

Select * From data

Where colA In ('AA', 'ZZ')
And colB = 'X'
And colC Like '%123%'


We can achieve the same result with XPath by using this expression below :

XPathNodeIterator xpIter = xpNav.Select("/root/row[(@colA = 'AA' or @colA = 'ZZ') and @colB = 'X' and contains(@colC, '123')]");

There is a lot of ways that we can use in XPath, you can find the complete references in http://www.w3.org/TR/xpath

XML is always an interesting type of data that we can use, there is a lot of database technologies nowadays which has actually supports XML type of data such as SQL2005 where I heard we can set the indexes in the XML type of field ;)

1 comments:

anon_anon said...

VTD-XML (http://vtd-xml.sf.net) claims the fatest XPath query performance ..

Post a Comment