Question

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.

Was it helpful?

Solution 4

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);

OTHER TIPS

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.

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(); 

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top