DataSet.DataTable.DataRow (Single) to XML String

clockwiseq picture clockwiseq · Feb 3, 2012 · Viewed 8k times · Source

I have strongly-typed datasets in the project that I am currently working on and I need to convert a DataRow object from the DataSet (only 1 DataTable in the DataSet) to an XML string. I attempted the following with only utter failure:

string originalXmlString = string.Empty;

DataSet ds = new DataSet();

ds.Tables.Add(this.ObjectDataRow.Table);
ds.Tables[0].ImportRow(this.ObjectDataRow);

using (StringWriter sw = new StringWriter())
{
    ds.Tables[0].WriteXml(sw);                         
    originalXmlString = sw.ToString();
}

req.OriginalDataRow = originalXmlString;

Any help would be greatly appreciated!

Thanks, Keith

Answer

clockwiseq picture clockwiseq · Feb 6, 2012

I was able to figure it out with the assistance of a MSDN page regarding the Clone() function.

The following code is revised and works great:

string originalXmlString = string.Empty;

DataSet ds = new DataSet();

//ds.Tables.Add(this.ObjectDataRow.Table);

ds.Tables.Add(this.ObjectDataRow.Table.Clone());

ds.Tables[0].ImportRow(this.ObjectDataRow);

using (StringWriter sw = new StringWriter())
{
    ds.Tables[0].WriteXml(sw);                         
    originalXmlString = sw.ToString();
}

req.OriginalDataRow = originalXmlString;