Possible to write XML to memory with XmlWriter?

旧城冷巷雨未停 提交于 2019-12-30 03:44:07

问题


I am creating an ASHX that returns XML however it expects a path when I do

XmlWriter writer = XmlWriter.Create(returnXML, settings)

But returnXML is just an empty string right now (guess that won't work), however I need to write the XML to something that I can then send as the response text. I tried XmlDocument but it gave me an error expecting a string. What am I missing here?


回答1:


If you really want to write into memory, pass in a StringWriter or a StringBuilder like this:

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

If you want to write it directly to the response, however, you could pass in HttpResponse.Output which is a TextWriter instead:

using (XmlWriter writer = XmlWriter.Create(Response.Output, settings))
{
    // Write into it here
}



回答2:


Something was missing on my side: flushing the XmlWriter's buffer:

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



回答3:


    StringBuilder xml = new StringBuilder();
    TextWriter textWriter = new StringWriter(xml);
    XmlWriter xmlWriter = new XmlTextWriter(textWriter);

Then, use the xmlWriter to do all the xml writing, and that writes it directly to the StringBuilder.

Edit: Thanks to Jon Skeet's comment:

    StringBuilder xml = new StringBuilder();
    XmlWriter xmlWriter = XmlWriter.Create(xml);



回答4:


The best way to do that is to write directly to the Response Output Stream. Its a stream that's built-in to ASP.NET to allow you to write whatever output as a stream, in this case you can write XML to it.



来源:https://stackoverflow.com/questions/683189/possible-to-write-xml-to-memory-with-xmlwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!