我正在创建一个返回XML的ASHX,但是当我这样做时它需要一条路径
XmlWriter writer = XmlWriter.Create(returnXML, settings)
但是returnXML现在只是一个空字符串(猜测它不起作用),但是我需要将XML编写成我可以作为响应文本发送的东西.我尝试了XmlDocument,但它给了我一个错误,期待一个字符串.我在这里错过了什么?
如果你真的想写入内存,请传入StringWriter
或者StringBuilder
像这样:
using System; using System.Text; using System.Xml; public class Test { static void Main() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; StringBuilder builder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(builder, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteStartElement("element"); writer.WriteString("content"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } Console.WriteLine(builder); } }
但是,如果要将其直接写入响应,则可以传入以下HttpResponse.Output
内容TextWriter
:
using (XmlWriter writer = XmlWriter.Create(Response.Output, settings)) { // Write into it here }
我身边缺少一些东西:刷新XmlWriter的缓冲区:
static void Main() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; StringBuilder builder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(builder, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("root"); writer.WriteStartElement("element"); writer.WriteString("content"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } Console.WriteLine(builder); }