Pregunta

Tenemos un proyecto VXML que un tercero analiza para proporcionarnos un sistema de navegación por teléfono. Les solicitamos que ingresen un código de identificación para dejar un mensaje, que luego será revisado por nuestra compañía.

Actualmente tenemos este trabajo de la siguiente manera:

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));

Solo mantengo esta aplicación, no la escribí ... pero la sección final me parece complicada.

Sé que está tomando el flujo de salida y alimentando el XML escrito en él ... pero ¿por qué está leyendo primero la cadena completa? ¿No es eso ineficiente?

¿Hay una mejor manera de escribir el código anterior?

¿Fue útil?

Solución

Sí, simplemente escriba directamente en la respuesta Salida (IO.StreamWriter) o OutputStream (IO.Stream):

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

Otros consejos

Después de eso solo puedo llamar a XML_Writer.Flush (), ¿verdad? Eso va a vaciar el XML a la corriente?

Puedes escribir directamente en el flujo de respuesta:

Response.Cache.SetCacheability (HttpCacheability.NoCache);

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

Para agregar configuraciones al escritor, es mejor utilizar el nuevo XmlWriterSettings class. Délo como un parámetro a la función XmlWriter.Create.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top