Nick
Nick

Reputation: 25828

Writing XML Sequentially

I'm using XML to record a stream of data. I know, there are better data formats out there but we have our reasons!

Normally I would use an XmlDocument to store xml data in memory and then write the whole thing out. That's not really much help here because how long we record the data stream for is not specified and probably unlikely to be fixed at any period short enough not to run out of memory.

What would the best approach be?

Thanks.

Upvotes: 0

Views: 416

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503974

Well, you could use an XmlWriter. The tricky bit will be knowing when to close the document - before you do so, it won't be valid XML; after you've done so, you can't append to it any more.

Note that you don't have to use XmlWriter directly. For example, using LINQ to XML (my preferred XML API; much nicer than the XmlDocument etc classes) you could create the writer, write out any "header" information (e.g. the opening tags for the container), then create XElement objects for each value you want to write, and call element.WriteTo(writer).

Sample code:

using System;
using System.Xml;
using System.Xml.Linq;

class Test
{
    static void Main() 
    {
        using (XmlWriter writer = XmlWriter.Create("test.xml"))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("log");
            writer.WriteStartElement("entries");

            for (int i = 0; i < 10; i++)
            {
                XElement element = new XElement("entry", "Entry " + i);
                element.WriteTo(writer);
            }
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }
    }
}

Upvotes: 3

Soonts
Soonts

Reputation: 21966

IMO the best approach is using the XmlWriter class, see this article.

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115887

XmlWriter provides a fast, non-cached, forward-only means of generating streams or files containing XML data.

Upvotes: 1

Related Questions