如何实现从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

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值