首先構建本身的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