开发者

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 wri开发者_如何学Gote 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.


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();
        }
    }
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜