可以使用XmlWriter将XML写入内存吗?

时间:2009-03-25 19:56:33

标签: c# asp.net xml xmlwriter

我正在创建一个返回XML的ASHX,但是当我这样做时它需要一个路径

XmlWriter writer = XmlWriter.Create(returnXML, settings)

但是returnXML现在只是一个空字符串(猜测不起作用),但是我需要将XML写入我可以作为响应文本发送的内容。我尝试了XmlDocument,但它给了我一个错误,期待一个字符串。我在这里缺少什么?

4 个答案:

答案 0 :(得分:43)

如果您真的想写入内存,请传递StringWriterStringBuilder,如下所示:

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

但是,如果您想直接将其写入回复,则可以传入HttpResponse.Output,而不是TextWriter

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

答案 1 :(得分:6)

我身边缺少一些东西:刷新XmlWriter的缓冲区:

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

答案 2 :(得分:3)

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

然后,使用xmlWriter完成所有xml编写,并将其直接写入StringBuilder。

编辑:感谢Jon Skeet的评论:

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

答案 3 :(得分:2)

最好的方法是直接写入响应输出流。它是一个内置于ASP.NET的流,允许您将任何输出写为流,在这种情况下,您可以将XML写入其中。