关于XMLTextWriters和Streams的问题

时间:2020-03-06 14:56:36  来源:igfitidea点击:

我们有一个第三方解析的VXML项目,以向我们提供电话导航系统。我们要求他们输入ID码以留下消息,稍后我们公司会对其进行审核。

目前,我们的工作如下:

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Stream m = new MemoryStream(); //Create Memory Stream - Used to create XML document in Memory
XmlTextWriter XML_Writer = new XmlTextWriter(m, System.Text.Encoding.UTF8);
XML_Writer.Formatting = Formatting.Indented;
XML_Writer.WriteStartDocument();
/* snip - writing a valid XML document */
XML_Writer.WriteEndDocument();
XML_Writer.Flush();
m.Position = 0;
byte[] b = new byte[m.Length];
m.Read(b, 0, (int)m.Length);
XML_Writer.Close();
HttpContext.Current.Response.Write(System.Text.Encoding.UTF8.GetString(b, 0, b.Length));

我只是在维护这个应用程序,我没有编写它……但是结尾部分对我来说似乎很麻烦。

我知道它正在获取输出流并将输入的XML馈入其中...但是为什么它首先读取整个字符串?那不是效率低下吗?

有没有更好的方法来编写上面的代码?

解决方案

是的,只需直接写到响应Output(IO.StreamWriter)或者OutputStream(IO.Stream):

XmlTextWriter XML_Writer = new XmlTextWriter(HttpContext.Current.Response.OutputStream, HttpContext.Current.Response.Encoding);
//...
XML_Writer.Flush();

之后,我可以只调用XML_Writer.Flush(),对吗?会将XML刷新到流中吗?

我们可以直接写入响应流:

`
Response.Cache.SetCacheability(HttpCacheability.NoCache);

XmlWriter XML_Writer = XmlWriter.Create(HttpContext.Current.Response.Output);
`

要将设置添加到编写器,最好使用较新的XmlWriterSettings类。将其作为参数提供给XmlWriter.Create函数。