首先构建本身的xmldocument,方式不少例如:node
XmlDocument xmldoc = new XmlDocument();
XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "GBK", null);app
//root node
XmlElement xmlelem = xmldoc.CreateElement("news");
xmldoc.AppendChild(xmlelem);//append the node to xmldocumentcode
……xml
而后用构建好的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 processingget
错误的作法是将xmldocument保存为OutputStream:xmldoc.Save(context.Response.OutputStream); it
关于为什么不能用xmldoc.Save(context.Response.OutputStream); 请看老外的一篇文章:io
http://stackoverflow.com/questions/543319/how-to-return-xml-in-asp-netclass