[ASP.NET]利用泛型產生XML
因為案子的關係,又有兩個不同的資料庫,搞的實在很複雜,而且有一台主機又慢,所以就想了個辦法,直接利用泛型來產生XML,不用在建立一個XML的檔案。
1.首先先打開一個新檔案Handler.ashx(泛型處理常式)
2.再來就是打入程式碼囉!
using System;
using System.Web;
using System.Xml;
using System.Data.SqlClient;
using System.Text;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.Clear();
context.Response.ContentType = "text/xml";
XmlTextWriter xmlTw = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);
xmlTw.WriteStartDocument();
xmlTw.WriteStartElement("NewsList");
//檔頭結束
using(SqlConnection conn = new SqlConnection("Server=LOCALHOST\\SQLEXPRESS;Database=DB;Trusted_Connection=True;"))
{
XmlDocument xml = new XmlDocument();
conn.Open();
string sql = "SELECT [id],[title], [stratdate], [enddate], [context], [pic], [viedo] FROM [news]";
SqlCommand command = new SqlCommand(sql, conn);
SqlDataReader dr = command.ExecuteReader();
while(dr.Read())
{
xmlTw.WriteStartElement("News");
xmlTw.WriteElementString("id",dr[0].ToString());
xmlTw.WriteElementString("title",dr[1].ToString());
xmlTw.WriteElementString("stratdate",dr[2].ToString());
xmlTw.WriteElementString("enddate",dr[3].ToString());
xmlTw.WriteElementString("context",dr[4].ToString());
xmlTw.WriteElementString("pic",dr[5].ToString());
xmlTw.WriteElementString("viedo",dr[6].ToString());
xmlTw.WriteEndElement();
}
dr.Dispose();
conn.Dispose();
conn.Close();
}
xmlTw.WriteEndElement();
xmlTw.Flush();
xmlTw.Close();
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
3.存檔再來就是打開這個檔案
4.完成了