Data Table to XML Genrate
///
/// Write out XML to a DataTable to a file in a controlled manner.
/// Use a XmlWriterSettings to control the output formatting.
///
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.CheckCharacters = true;
settings.CloseOutput = true;
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Encoding = Encoding.UTF8;
settings.Indent = false;
settings.NewLineHandling = NewLineHandling.Replace;
settings.NewLineOnAttributes = true;
settings.OmitXmlDeclaration = true;
using (var sw = new StringWriter())
{
using (var writer = XmlWriter.Create(sw))
{
// Build Xml with xw.
writer.WriteStartDocument(true);
WriteTable(writer, table);
writer.WriteEndDocument();
}
return sw.ToString();
}
}
private static void WriteTable(XmlWriter writer, DataTable table)
{
//
writer.WriteStartElement("DocumentElement");
foreach (DataRow row in table.Rows)
{
//
writer.WriteStartElement(table.TableName);
foreach (DataColumn column in table.Columns)
{
writer.WriteStartElement(column.ColumnName);
writer.WriteValue(row[column].ToString());
writer.WriteEndElement();
}
//
writer.WriteEndElement();
}
//
writer.WriteEndElement();
}