Reputation: 31
I would like to write a method to convert a asp.net datatable into XML document. What is the best way to achieve it? Apologize it it is very basic question.
Thanks in advance.
Upvotes: 2
Views: 4822
Reputation:
You can use "WriteXml"
method to convert your datatable into XML document.
Example:
DataTable dt = new DataTable("Product");
DataColumn dc = new DataColumn();
dc.ColumnName = "ProductID";
dc.DataType = typeof(int);
dt.Columns.Add(dc);
DataColumn dc2 = new DataColumn();
dc2.ColumnName = "ProductName";
dc2.DataType = typeof(string);
dt.Columns.Add(dc2);
dt.Rows.Add(new object[] { "1", "CShap In Depth By Jon Skeet" })
dt.WriteXml("{path to save your xml file}\\documentname.xml");
But still you want extension method you can use the following sample code (Not Tested)
(taken from http://www.extensionmethod.net/csharp/datatable/toxml )
public static XDocument ToXmlDocument(this DataTable dataTable, string rootName)
{
var XmlDocument = new XDocument
{
Declaration = new XDeclaration("1.0", "utf-8", "")
};
XmlDocument.Add(new XElement(rootName));
foreach (DataRow row in dataTable.Rows)
{
XElement element = null;
if (dataTable.TableName != null)
{
element = new XElement(dataTable.TableName);
}
foreach (DataColumn column in dataTable.Columns)
{
element.Add(new
XElement(column.ColumnName, row[column].ToString().Trim(' ')));
}
if (XmlDocument.Root != null) XmlDocument.Root.Add(element);
}
return XmlDocument;
}
}
Upvotes: 1
Reputation: 166366
Have a look at using DataTable.WriteXml Method
Writes the current contents of the DataTable as XML.
More specifically the overloads using XmlWriteMode Enumeration
Using the option WriteSchema
Writes the current contents of the DataSet as XML data with the relational structure as inline XSD schema. If the DataSet has only a schema with no data, only the inline schema is written. If the DataSet does not have a current schema, nothing is written.
Upvotes: 1