如何实现从XML文档转换到DataSet

如何实现从XML文档转换到DataSet

服装设计 杭州有线电视 杭州标志设计 cocktail dress Solar Water Heater
 
以下是代码片段:
    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;
  }
  }
  }
  }
  }

转载于:https://www.cnblogs.com/webearly/archive/2011/06/09/2076567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值