一般处理程序ashx输出XML

首先构建自己的xmldocument,方式很多例如:

XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "GBK", null);

//root node
XmlElement xmlelem = xmldoc.CreateElement("news");
xmldoc.AppendChild(xmlelem);//append the node to xmldocument

……

然后用构建好的xmldocument,输出XML字符串,方法如下:

context.Response.Clear();
context.Response.ContentType = "text/xml"; //must be 'text/xml'
context.Response.ContentEncoding = System.Text.Encoding.UTF8; //we'd like UTF-8
xmldoc.Save(context.Response.Output); //save to the text-writer
context.Response.End(); //optional: will end processing

错误的做法是将xmldocument保存为OutputStream:xmldoc.Save(context.Response.OutputStream); 

关于为何不能用xmldoc.Save(context.Response.OutputStream); 请看老外的一篇文章:

http://stackoverflow.com/questions/543319/how-to-return-xml-in-asp-net

原文地址:https://www.cnblogs.com/zhangwei412827/p/3359415.html