如何实现从XML文档转换到DataSet
如何实现从XML文档转换到DataSet
以下是代码片段: using System; using System.Xml; using System.Data; using System.Text; using System.IO; namespace NET.MST.Tenth.XmlAndDataSet { partial class XmlAndDataSet { static void Main(string[] args) { Console.WriteLine("从XML文档转换到DataSet:"); DataSet ds = ConvertXMLFileToDataSet("..\\..\\Test.xml"); PrintDataSet(ds); Console.WriteLine("从DataSet转换回XML文档:"); ConvertDataSetToXML(ds).Save(Console.Out); Console.Read(); } /// /// 打印DataSet /// /// DataSet对象 static void PrintDataSet(DataSet ds) { foreach (DataTable table in ds.Tables) { Console.WriteLine("表{0}:", table.TableName); foreach (DataColumn column in table.Columns) { Console.Write("{0}({1}) ", column.ColumnName, column.ColumnMapping.ToString()); } Console.Write("\r\n"); foreach (DataRow row in table.Rows) { foreach (DataColumn col in table.Columns) { Console.Write("{0} ", row[col.ColumnName].ToString().Trim()); } Console.Write("\r\n"); } } } } partial class XmlAndDataSet { /// /// 将xml文件转换为DataSet /// public static DataSet ConvertXMLFileToDataSet(string xmlFile) { //读入XML文档 XmlDocument xml = new XmlDocument(); xml.Load(xmlFile); DataSet result = new DataSet(); using (StringReader stream = new StringReader(xml.InnerXml)) { using (XmlTextReader reader = new XmlTextReader(stream)) { result.ReadXml(reader); return result; } } } /// /// 将DataSet转换为xml对象字符串 /// public static XmlDocument ConvertDataSetToXML(DataSet ds) { using (MemoryStream stream = new MemoryStream()) { //通过XmlTextWriter来生成XML using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode)) { //DataSet转换为XML文档 ds.WriteXml(writer); //从流中读出数据 int count = (int)stream.Length; byte[] arr = new byte[count]; stream.Seek(0, SeekOrigin.Begin); stream.Read(arr, 0, count); XmlDocument result = new XmlDocument(); result.LoadXml(""+ Encoding.Unicode.GetString(arr).Trim()); return result; } } } } } |