- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data.SqlClient;
- using System.Data;
- using System.Xml;
- using System.Xml.Linq;
- using System.Text;
- public partial class Test_tsDataTabletoXML : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- try
- {
- SqlConnection cn = new SqlConnection();
- cn.ConnectionString = "Data Source=localhost;Initial Catalog=db1;Persist Security Info=True;User ID=sa;Password=123456";
- SqlCommand cmd = new SqlCommand();
- cmd.Connection = cn;
- cmd.CommandText = "select * from Product";
- cn.Open();
- SqlDataAdapter da = new SqlDataAdapter();
- da.SelectCommand = cmd;
- DataSet ds = new DataSet("ds1");
- da.Fill(ds, "Product");
- DataTable dt = ds.Tables["Product"];
- // XML Setting
- XmlWriterSettings settings = new XmlWriterSettings();
- settings.Indent = false;
- settings.Encoding = settings.Encoding = Encoding.GetEncoding("utf-8");
- // XML Write
- XElement tElement = new XElement("DataTable", "");
- using (XmlWriter xmlWriter = XmlWriter.Create("c:\\Product.xml", settings))
- {
- // Write the data set to the writer.
- tElement = DataTableToXml(dt, "root");
- tElement.WriteTo(xmlWriter);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// DataTable to XML
- /// </summary>
- /// <param name="pAttributeTable"></param>
- /// <param name="tParentTag"></param>
- /// <returns></returns>
- private XElement DataTableToXml(DataTable pAttributeTable, string tParentTag)
- {
- if (pAttributeTable == null)
- return null;
- XElement tParent = null;
- try
- {
- tParent = new XElement(tParentTag); // 集合Tag的名字
- //每個DataRow為屬性分類
- foreach (DataRow tRow in pAttributeTable.Rows)
- {
- XElement tChild = new XElement("DataRow");
- //每個DataRow的DataColumn為屬性分類裡的項目
- foreach (DataColumn tColumn in pAttributeTable.Columns)
- {
- tChild.Add(new XElement(tColumn.ColumnName, tRow[tColumn]));
- }
- tParent.Add(tChild);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- return tParent;
- }
- }
2013年6月4日 星期二
C# DataTable to XML
[C#]DataTable to XML
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言