Reusing the XmlTextWriter Class

Is it possible to reuse the same instance of the XmlTextWriter class to generate 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
...
+3
source share
3 answers

The simple answer is yes, it is possible.

But this will be achieved if the underlying stream does not point to a file. MemoryStream can be a good example of this.

Since MemoryStream saves the stream “in memory”, you can write many XML files with your XmlTextWriter and after completing each document make MemoryStream.ToArray () and pass it as an argument to File.WriteAllBytes.

After writing all the bytes, you clear your memory stream.

, MemoryStream.SetLength 0 :

XmlTextWriter:

File.WriteAllBytes:

XmlTextWriter

@NigelTouch :

, , , , , WriteStartElement(), Flush() Writer 0, Writer WriteState of Element. , " > " ().

@Mike-EEE :

. , ,

, XmlTextWriter, , :

    using(MemoryStream stream = new MemoryStream())
    using(StreamReader streamReader = new StreamReader(stream))
    using(XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
    {
        writer.WriteStartDocument(true);
        writer.WriteStartElement("a");

        try 
        {
            throw new Exception();
        }
        catch 
        {
            // This line makes de magic: ending the document
            // avoids the issue mentioned by @NigelTouch
            writer.WriteEndDocument();
            writer.Flush();
            stream.SetLength(0);
        }


        writer.WriteStartDocument(true);
        writer.WriteStartElement("b");
        writer.WriteEndElement();
        writer.Flush();

        stream.Position = 0;

        Console.WriteLine(streamReader.ReadToEnd());

    }
+2

XmlTextWriter :

, , , , XML-, W3C (XML) 1.0 XML.

( )

Reset . , reset .

, .

+1

I suggest flush to do something you ask for. Just create and extract XML, flush, rince, repeat;)

Greetings.

0
source

Source: https://habr.com/ru/post/1790401/


All Articles