c# xml与dataset互转

//将xml对象内容字符串转换为DataSet
public static DataSet ConvertXMLToDataSet(string xmlData)
{
xmlData = "<" + xmlData.Substring(xmlData.IndexOf('<') + 1);
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet();
stream = new StringReader(xmlData);
//从stream装载到XmlTextReader
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
return xmlDS;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (reader != null) reader.Close();
}
}

 


//将DataSet转换为xml对象字符串
public static string ConvertDataSetToXML(DataSet xmlDS)
{
MemoryStream stream = null;
XmlTextWriter writer = null;

try
{
stream = new MemoryStream();
//从stream装载到XmlTextReader
writer = new XmlTextWriter(stream, Encoding.UTF8);

//用WriteXml方法写入文件.
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().Replace("\n", "");
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (writer != null) writer.Close();
}
}

 

上一篇:Python CSV写入操作


下一篇:1071 Speech Patterns (25分)