[ASP.NET]將資料轉為 XML 顯示

  • 3006
  • 0
  • 2014-02-25

[ASP.NET]將資料轉為 XML 顯示

這是個簡易的建立 XML 範例

作法係將資料庫資料取出後,建立

想要的 XML 的格式,再 Response 出來

作法是先將頁面資料清空,如下

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Code Behind 部分


    string connstring = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {

        string str = "SELECT ProductID,CategoryID,ProductName,QuantityPerUnit,UnitsInStock,UnitPrice from Products WHERE Discontinued = 0";
        DataTable dt = GetDTConn(str);
        dt.Dispose();

        XmlWriterSettings xmlset = new XmlWriterSettings();
        Encoding enc = Encoding.GetEncoding("utf-8");       //設定編碼
        xmlset.Indent = true;       //縮排項目
        xmlset.OmitXmlDeclaration = false;      // XML 宣告
        xmlset.NewLineOnAttributes = true;      //將屬性寫在新行
        xmlset.Encoding = enc;
        
        MemoryStream ms = new MemoryStream();
        XmlWriter writer = XmlWriter.Create(ms, xmlset);
        
        writer.WriteStartDocument();
        writer.WriteStartElement("Northwind");
        foreach (DataRow dr in dt.Rows)
        {
            writer.WriteStartElement("Products");
            writer.WriteAttributeString("ProductID", dr["ProductID"].ToString());
            writer.WriteAttributeString("CategoryID", dr["CategoryID"].ToString());
            writer.WriteAttributeString("ProductName", dr["ProductName"].ToString());
            writer.WriteAttributeString("QuantityPerUnit", dr["QuantityPerUnit"].ToString());
            writer.WriteAttributeString("UnitsInStock", dr["UnitsInStock"].ToString());
            writer.WriteAttributeString("UnitPrice", dr["UnitPrice"].ToString());
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();
        writer.Close();

        string result = enc.GetString(ms.ToArray());
        HttpContext.Current.Response.ContentType = "text/xml";
        HttpContext.Current.Response.Write(result);
    }

    //資料連結 回傳 DataTable
    protected DataTable GetDTConn(string str)
    {
        using (SqlConnection con = new SqlConnection(connstring))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(str, con))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
        }
    }

輸出的結果

image

範例檔案 下載