XmlWriter.Create(TextWrite output)创建一个实例,可以将Response.Output 直接传入,这样编码是按web.config里面的配置或默认(utf-8)设置的,使用Response.ContentEncoding = Encoding.UTF8; 可以设置生存xml数据的编码,不过需要放在,XmlWriter.Create之前 xmlWriter在输出完成后,请使用Flush以保证内容全部输出.XmlWriterSettings 用来设置Xml 文本串的一些格式(在用记事本查看是的情况,而IE等可以自动进行格式化显示),比方缩进,注意也要放在Create方法前设置.
代码入下:
XmlWriterSettings s = new XmlWriterSettings(); s.Indent = true; XmlWriter w = XmlWriter.Create(Response.Output,s); w.WriteStartDocument(); w.WriteStartElement("rss"); w.WriteAttributeString("version", "2.0"); w.WriteStartElement("channel"); w.WriteElementString("title", "神鹰医药招商网医药资讯"); w.WriteElementString("link", "http://news.gyzs.net"); w.WriteElementString("description", "医药信息,医药网络营销售"); WriteItem(w,n,flag); w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close();
Response.ContentType = "text/xml"; Response.Flush(); Response.End();
代码2:
private void WriteItem(XmlWriter w,int num,bool flag){ using (IDataReader dr = Article.Query().SetTop(num.ToString()).SetSelectList("ID,Title,Summary,AddTime").ORDER_BY("Id Desc").ExecuteReader()) { while (dr.Read()) { w.WriteStartElement("item"); w.WriteAttributeString("id", dr["Id"].ToString()); //title w.WriteStartElement("title"); w.WriteCData(dr["title"].ToString()); w.WriteEndElement(); //link w.WriteStartElement("link"); w.WriteString( "http://news.gyzs.net/article/" + ((DateTime)dr["AddTime"]).ToString("yyyy-MM-dd") + "/" + dr["id"].ToString() + ".html" ); w.WriteEndElement(); //description w.WriteStartElement("description"); if (flag) { w.WriteCData(dr["Summary"].ToString()); } w.WriteEndElement(); //pubDate w.WriteStartElement("pubDate"); w.WriteString(((DateTime)dr["AddTime"]).ToString() ); w.WriteEndElement(); w.WriteEndElement(); } }
---------------------下面使用MemoryStream ,StreamWriter 来完成同样的任务
//MemoryStream ms = new MemoryStream(); //StreamWriter sw = new StreamWriter(ms, Encoding.GetEncoding("gb2312")); //XmlWriter w = XmlWriter.Create(sw);
//StreamReader sr = new StreamReader(ms, Encoding.GetEncoding("gb2312")); //ms.Seek(0, SeekOrigin.Begin); //string v = sr.ReadToEnd(); //sr.Close(); //Response.Write(v);