.Net 的XML与DataSet 相互转换代码模版:

public static DataSet ConvertXMLFileToDataSet(string xmlText)
{

StringReader stream = null;

     XmlTextReader reader = null;

     try

{

         DataSet xmlDS = new DataSet();

stream = new StringReader(xmlText);

reader = new XmlTextReader(stream);

xmlDS.ReadXml(reader);

reader.Close();

         return xmlDS;

}

     catch (System.Exception ex)

{

reader.Close();

}

}


public static string DataToXml(DataSet ds)

{

     if (ds != null && ds.Tables.Count > 0)

{

         MemoryStream ms = null;

         XmlTextWriter XmlWt = null;

         try

{

ms = new MemoryStream();
              
XmlWt = new XmlTextWriter(ms, Encoding.Unicode);

//获取ds中的数据

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)

{


}

finally

{

if (XmlWt != null)

{

XmlWt.Close();

ms.Close();

}

}

}

else
       
return “”;
        
}

 

 

 

发表评论

电子邮件地址不会被公开。