附1.将DataTable转成XML示例(1)protected XmlDocument MyConvertDataTableToXML(DataTable xmlDS)
{
XmlDocument doc = new XmlDocument();
StringBuilder xmlStr = new StringBuilder("<?xml version='1.0' encoding='utf-8'? ><detail >");
foreach(DataRow row in xmlDS.Rows)
{
xmlStr.Append("<row ");
for(int i=0;i < xmlDS.Columns.Count;i++)
{
xmlStr.Append(xmlDS.Columns[i].ColumnName + "='" + row[xmlDS.Columns[i].ColumnName].ToString() + "' ");
}
xmlStr.Append("/ >");
}
xmlStr.Append("</detail >");
doc.LoadXml(xmlStr.ToString());
return doc;
}
附2.将DataTable转成XML示例(2)private string ConvertDataTableToXML(DataTable xmlDS)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
writer = new XmlTextWriter(stream, Encoding.UTF8);
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding();
return utf.GetString(arr).Trim();
}
catch
{
return String.Empty;
}
finally
{
if (writer != null) writer.Close();
}
}
附3.将XML转成DataTable示例private DataSet ConvertXMLToDataSet(string xmlData)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet();
stream = new StringReader(xmlData);
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
return xmlDS;
}
catch (Exception ex)
{
string strTest = ex.Message;
return null;
}
finally
{
if (reader != null)
reader.Close();
}
}
附4.将DataReader装载到DataTableSqlDataReader currentSdr = currentCmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(currentSdr)