关于XMLTextWriters和Streams的问题

时间:2008-09-30 19:46:54

标签: asp.net stream xmltextwriter

我们有一个VXML项目,第三方解析为我们提供电话导航系统。我们要求他们输入身份验证码以留言,我们公司稍后会对此进行审核。

我们目前的工作方式如下:

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提供给它...但为什么它首先读取整个字符串?效率不高吗?

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

之后我可以调用XML_Writer.Flush(),对吧?那会把XML刷新到流吗?

答案 2 :(得分:0)

您可以直接写入回复流:

Response.Cache.SetCacheability(HttpCacheability.NoCache);

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

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