1。DataSet转XML
#region DataToXml
/// <summary>
/// 将DataSet对象转换成XML字符串
/// </summary>
/// <param name="ds">DataSet对象</param>
/// <returns>XML字符串</returns>
public string DataToXml(DataSet ds)
{
if (ds != null && ds.Tables.Count > 0)
{
MemoryStream ms = null;
XmlTextWriter XmlWt = null;
try
{
ms = new MemoryStream();
//根据ms实例化XmlWt
XmlWt = new XmlTextWriter(ms, Encoding.Unicode);
//获取ds中的数据
//dt.WriteXml(XmlWt);
ds.WriteXml(XmlWt);
int count = (int)ms.Length;
byte[] temp = new byte[count];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(temp, 0, count);
//返回Unicode编码的文本
UnicodeEncoding ucode = new UnicodeEncoding();
string returnValue = ucode.GetString(temp).Trim();
return returnValue;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
//释放资源
if (XmlWt != null)
{
XmlWt.Close();
ms.Close();
}
}
}
else
{
return "";
}
}
#endregion
//Add End
}
2。XML转DataSet
则
DataSet dsResult=XMLHelper.XMLToDataSet(param);
其中param参数为类似
<RECEIVABLE_IFACE><SECURITY_CONTROL><SYSTEM_CODE>HELLO</SYSTEM_CODE></SECURITY_CONTROL></RECEIVABLE_IFACE>的样子
或者:
#region Xml To DataSet
public static DataSet ConvertXMLFileToDataSet(string xmlText)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
//XmlDocument xmld = new XmlDocument();
//xmld.Load(xmlFile);
DataSet xmlDS = new DataSet();
//stream = new StringReader(xmld.InnerXml);
stream = new StringReader(xmlText);
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
reader.Close();
return xmlDS;
}
catch (System.Exception ex)
{
reader.Close();
throw ex;
}
}
#endregion