Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to write XML to memory with XmlWriter?

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?

like image 681
MetaGuru Avatar asked Mar 25 '09 19:03

MetaGuru


3 Answers

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
}
like image 142
Jon Skeet Avatar answered Oct 12 '22 23:10

Jon Skeet


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);
}
like image 6
Loïc Avatar answered Oct 12 '22 21:10

Loïc


    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);
like image 3
BFree Avatar answered Oct 12 '22 22:10

BFree