Search code examples
c#.netxmlxmlwriter

Building an XML file iteratively with XmlWriter


I want to be able to use XmlWriter (C#, .NET) to create an XML document with multiple calls to a method that generates XML and then a single call to a final method that closes everything off. When I try to call this method multiple times:

private void SiblingGenerator(List<XmlNode> XMLList, XmlWriter textWriter,
    string newPath, FileInfo fi)
{
    if (fi.Length == 0)
    {
        MessageBox.Show("file doesn't exist");

        textWriter.WriteStartDocument();
        textWriter.WriteStartElement("batch");
        //...
    }

    // ...
}

...it returns an error saying that WriteStartDocument needs to be the first call.

It seems like the calls to the textWriter aren't actually being written because on each subsequent call the document starts over again.

Can anyone tell me why this is happening?


Solution

  • A XmlWriter is forward only and cannot be reused. You shouldn't call WriteStartDocument multiple times on the same instance of this class. Because it is an argument of your method it is the caller that must take care of handling the life-cycle of the writer.

    using (var writer = XmlWriter.Create("foo.xml"))
    {
        SiblingGenerator(XMLList, writer, newPath, fi);
    }
    

    If you need to reuse the SiblingGenerator function multiple times then you might want to externalize the call of the WriteStartDocument method:

    using (var writer = XmlWriter.Create("foo.xml"))
    {
        writer.WriteStartDocument();
        SiblingGenerator(XMLList, writer, newPath, fi);
        SiblingGenerator(XMLList, writer, newPath, fi);
        ...
        writer.WriteEndDocument();
    }