关于 XMLTextWriters 和 Streams 的问题
我们有一个由第三方解析的 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 输入到其中...但为什么它首先读取整个字符串? 这不是效率低下吗?
上面的代码有更好的写法吗?
We have a VXML project that a 3rd party parses to provide us with a phone navigation system. We require them to enter an id code to leave a message, which is later reviewed by our company.
We currently have this working as follows:
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));
I'm just maintaining this app, I didn't write it...but the end section seems convoluted to me.
I know it's taking the output stream and feeding the written XML into it...but why is it first reading the entire string? Isn't that inefficient?
Is there a better way to write the above code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,只需直接写入响应
Output
(IO.StreamWriter) 或OutputStream
(IO.Stream):Yes, just write directly to the Response
Output
(IO.StreamWriter) orOutputStream
(IO.Stream):之后我可以调用 XML_Writer.Flush(),对吧? 这会将 XML 刷新到流中吗?
After that I can just call XML_Writer.Flush(), right? That'll flush the XML to the stream?
您可以直接写入响应流:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
XmlWriter XML_Writer = XmlWriter.Create(HttpContext.Current.Response.Output);
要向编写器添加设置,您最好使用较新的 XmlWriterSettings 类。 将其作为参数提供给 XmlWriter.Create 函数。
You can write directly to the response stream:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
XmlWriter XML_Writer = XmlWriter.Create(HttpContext.Current.Response.Output);
To add settings to the writer you are better off using the newer XmlWriterSettings class. Give it as a parameter to the XmlWriter.Create function.