stream|xml
MemoryStream对象提供了无需进行IO就可以创建Stream的方法,XmlTextWriter和XmlReader提供快速书写和读取XML内容的方法,结合MemoryStream,就可以直接在内存中构造XmlTextWriter,并用XmlReader进行读取。
使用MemoryStream和XmlTextWriter进行书写XML,需要注意两点:XmlTextWriter.Flush操作和重设MemoryStream.Position = 0。
C#
<% Page Language="C#"%>
<% Import Namespace="System.Xml" %>
<% Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/xml";
MemoryStream msXml = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(msXml, Encoding.UTF8);
xmlWriter.WriteStartElement("rss");
xmlWriter.WriteAttributeString("version", "2.0");
xmlWriter.WriteStartElement("channel");
xmlWriter.WriteElementString("title", "【孟宪会之精彩世界】");
xmlWriter.WriteElementString("link", "http://dotnet.aspx.cc/Rss.aspx");
xmlWriter.WriteElementString("description", "NET开发技术。");
xmlWriter.WriteElementString("language", "zh-CN");
xmlWriter.WriteElementString("copyright", "Copyright 1999-2007【孟宪会之精彩世界】");
xmlWriter.WriteElementString("managingEditor", "amxh[AT]21cn.com");
xmlWriter.WriteStartElement("image");
xmlWriter.WriteElementString("title", "【孟宪会之精彩世界】");
xmlWriter.WriteElementString("width", "144");
xmlWriter.WriteElementString("height", "35");
xmlWriter.WriteElementString("link", "http://dotnet.aspx.cc/");
xmlWriter.WriteElementString("url", "/XrssFile/2006-12/28/2006122823304840.gif");
xmlWriter.WriteEndElement();
//循环读出数据库内容列表,忽略
//while (objReader.Read())
//{
// xmlWriter.WriteStartElement("item");
// xmlWriter.WriteElementString("title", objReader.GetString(0));
// xmlWriter.WriteElementString("description", objReader.GetString(1));
// xmlWriter.WriteElementString("link", "http://dotnet.aspx.cc/article/a933b187-06c3-4263-9eec-414a54d9c815/read.aspx");
// xmlWriter.WriteElementString("pubDate", objReader.GetDateTime(3).ToString("G"));
// xmlWriter.WriteEndElement();
/