tags:

views:

2845

answers:

4

Whats the best way to read Xml from either an XmlDocument or a String into a DataGrid?

Does the xml have to be in a particular format?

Do I have to use A DataSet as an intermediary?

I'm working on a client that consumes Xml sent over from a Server which is being developed by one of my colleagues, I can get him to change the format of the Xml to match what a DataGrid requires.

+1  A: 

It depends on which version of .NET you are running on. If you can use Linq2Xml then it is easy. Just create an XDocument and select the child nodes as a list of an anonymous type.

If you can't use Linq2Xml then you have a few other options. Using a DataSet is one, this can work well, but it depends on the xml you are receiving. An other option is to create a class that describes the entity you will read from the xml and step through the xml nodes manually. A third option would be to use Xml serialization and deserialize the xml into a list of objects. This can work well as long as you have classes that are setup for it.

The easiest option will be either to create an XDocument or to create a DataSet as you suggest.

Rune Grimstad
+1  A: 

Obviously your XML needs to be valid :)

After that, define a dataset, define a datagrid. Use the readXML method on the dataset to fill the dataset with your XML, finish with a dataBind and you are good to go.

DataSet myDataSet = new DataSet();
myDataSet .ReadXml(myXMLString);
myDataGrid.DataSource = myDataSet ; 
myDataGrid.DataBind();
Roel Snetselaar
DataSet.ReadXml takes a file name as an argument not Xml String...
Omar Kooheji
Is there a ParseXml version?
Will
No but see my other answer which uses an XmlText Reader.
Omar Kooheji
@Omar you are correct, my mistake, the different overloads can be found here btw: http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx
Roel Snetselaar
A: 

You can simply use the XmlDatasource object as the grid's data source. That allows you to set the file and the XPath, in order to choose the XML that is the soure of your data. You can then use the <%# XPath="blah"%> function to write out your data explicitely, if you like.

darasd
A: 

We have a partial answer to get the data into a dataset but it reads it in as a set of tables with relational links.

        DataSet ds = new DataSet();
        XmlTextReader xmlreader = new XmlTextReader(xmlSource, XmlNodeType.Document, null);
        ds.ReadXml(xmlreader);
Omar Kooheji
You don't want (all) the tables or the links?
Henk Holterman
I'd like to join the tables into a single table...
Omar Kooheji