Is it possible to reuse the same instance of XmlTextWriter class for generating more xml documents? I mean something like this:
XmlTextWriter writer = new XmlTextWriter();
writer.WriteStartDocument();
writer.WriteStartElement("Message1");
writer.WriteEndElement();
writer.WriteEndDocument();
// do something with xml created
...
writer.Reset() // ?
writer.WriteStartDocument();
writer.WriteStartElement("Message2");
writer.WriteEndElement();
writer.WriteEndDocument();
// do something with xml created
...
Easy answer: yes, it's possible to do that.
But this would be achived if underlying stream isn't pointing to a file. MemoryStream could be a good example of that.
As MemoryStream saves the stream "in memory", you can write a lot of XML files with your XmlTextWriter and after ending each document, do a MemoryStream.ToArray() and give it as argument for File.WriteAllBytes.
After writing all bytes, you'd clear your memory stream.
You can clear your memory stream by calling MemoryStream.SetLength method and give 0 as length:
Read more here, about stream overload of XmlTextWriter constructor:
And this for File.WriteAllBytes:
About some concerns when reusing an
XmlTextWriter
Some years ago @NigelTouch raised a concern on some comment:
And some hours ago, @Mike-EEE got into the same issue:
BTW, a bit of trial-error got me to recover a given
XmlTextWriter
to reuse it as many times as you want: