cerhart
cerhart

Reputation: 391

Converting XML to a DataTable

This is something I will be able to do, but I'm curious to hear people's ideas about the best way to do it. I have an XML file sitting on the web at http://www.someplace.com/file and I am writing a web service that will take that data and convert it to a DataTable object, then return the datatable. We're using c# 3.5. What do you think is the best way to tackle this?

Upvotes: 2

Views: 5904

Answers (3)

Vitaliy Ulantikov
Vitaliy Ulantikov

Reputation: 10514

You can parse your XML to DataSet and get it's DataTable:

DataSet dataSet = new DataSet();
dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema);

Upvotes: 0

MusiGenesis
MusiGenesis

Reputation: 75296

DataTable dt = new DataTable();
dt.ReadXml("c:myxml.xml");

Upvotes: 2

marc_s
marc_s

Reputation: 754230

Simply download the XML file to your local disk, and then create the DataTable, and call DataTable.ReadXml(filename) on it..... or am I missing something....

The DataTable.ReadXml even supports a stream - so you could hook it up directly to your WebResponse stream from downloading the XML from that URL.

(this is untested, from memory - but should give you an idea how to approach this):

DataTable myDataTable = new DataTable();

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://someplace/somefile.xml");
myRequest.Method = "GET";

WebResponse myResponse;
try
{
   myResponse = myRequest.GetResponse();

   using (Stream responseStream = myResponse.GetResponseStream())
   { 
      myDataTable.ReadXml(responseStream);
   }
}
catch
{ }

Marc

Upvotes: 4

Related Questions