Theresa
Theresa

Reputation: 21

XmlWriter to both String and File

Can I use an XmlWriter to write to both a file and a string?

When writing to a file I do this:

using (var xw = XmlWriter.Create("myFile.xml"))
{
    //Build the xml
} 

And when writing to a string I do this:

using (var sw = new StringWriter())
{
    using (var xw = XmlWriter.Create(sw))
    {
        // Build the xml
    }
    return sw.ToString();
}

But can I write to both a file and a string with the same XmlWriter instance?

Upvotes: 0

Views: 1441

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Create a composite XmlWriter which wraps many XmlWriter instances.

public class CompositeXmlWriter : XmlWriter
{
    private readonly IEnumerable<XmlWriter> writers;
    public CompositeXmlWriter(IEnumerable<XmlWriter> writers)
    {
        this.writers = writers;
    }

    public override void WriteStartDocument()
    {
        foreach (var writer in writers)
        {
            writer.WriteStartDocument();
        }
    }

    public override void WriteEndDocument()
    {
        foreach (var writer in writers)
        {
            writer.WriteEndDocument();
        }
    }

    ...Implement all other methods
}

Create your CompositeXmlWriter with other XmlWriters.

using (var xw = new CompositeXmlWriter(new[] { XmlWriter.Create("myFile.xml"), XmlWriter.Create(new StringWriter())})
{
    //Build the xml
}

Now whatever written in xw will be written in all the XmlWriters.

Upvotes: 0

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

You could create a method like this:

private static void WriteXML(TextWriter writer)
{
    using (var xw = XmlWriter.Create(writer))
    {
        // Build the xml
    }
}

And then call it like:

using (StreamWriter sw = new StreamWriter(...))
    WriteXML(sw);

to write a file or

string xml = String.Empty;
using (StringWriter sw = new StringWriter())
{
    WriteXML(sw);
    xml = sw.ToString();
}

To create the string.

You could even create helper methods:

private static void WriteXMLFile(string fileName)
{
    using (StreamWriter sw = new StreamWriter(...))
        WriteXML(sw);
}

private static string GetXML()
{
    using (StringWriter sw = new StringWriter())
    {
        WriteXML(sw);
        return sw.ToString();
    }
}

Upvotes: 1

Related Questions