.net DataSet和XML的相互转换


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值