ASP.NET----从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();
}
/// <summary>
/// 打印DataSet
/// </summary>
/// <param name="ds"> DataSet对象 </param>
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
{
/// <summary>
/// 将xml文件转换为DataSet
/// </summary>
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;
}
}
}
/// <summary>
/// 将DataSet转换为xml对象字符串
/// </summary>
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(
" <?xml version='1.0' encoding='GB2312'?> " +
Encoding.Unicode.GetString(arr).Trim());
return result;
}
}
}
}
}

你可能感兴趣的:(asp.net)