In my previous blog I explained how to use XQuery in .NET platform. You can see it from here. In this blog I will explain how to display the result of a XQuery by using DataGrid in .NET.
As a beginning we have a string value which has a format like XML and holds the result of our XQuery like:
Our main concern is to use DataSet.ReadXML() method but the problem is this method does not take String value as an input. It takes one of the File, Stream, XMLReader or TextReader typed objects. So how can we use it ?
- First we can write our String value to a new file which we can create on fly then give it to method.
- We can create either of XMLReader and TextReader objects and assign our file to these objects the put the output to out method.
I think these solutions are to complicated and there are too much steps on them. While I was looking for any neat solution, I found using Stream isn`t a bad idea to be used here. Also it was my only choice left.
So let`s start;
- First we need to create a MemoryStream object, because ReadXML() takes Stream typed objects.
- Constructor of the MemoryStream class is accepting byte that we can easily cast our String value.
This is how we cast our String value:
As a result we are getting our Stream value like:
MemoryStream mstream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(result));
After we filled up our Stream object, we need to put it into ReadXML() method of our DataSet;
DataSet ds = new DataSet(); ds.ReadXml(mstream);
Now we can use this DataSet where ever we want, for example we can easily bind it to a DataGrid.
If you want to learn how to bind this DataSet to a DataGrid, look for my post about it..