Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

Does XDocument.Load loads all data into memory?

I must read all first level nodes of the root node of large xml file that looks like the following:

<root>
 <record n="1"><a/><b/><c/></record>
 <record n="2"><a/><b/><c/></record>
 <record n="3"><a/><b/><c/></record>
</root>

And my code looks like:

var xml = XDocument.Load(filename);

var firstNode = xml?.Root?.Descendants()?.FirstOrDefault();

var elements = firstNode?.Elements();

I just need to get the first child of the root and all first level descendants of it. This code works fine, but the question is: is it safe to read like this? I guess it does not load all data into memory - only the structure of the xml file?

As I see memory is not increased while debugging. It only explodes if I actually try to see what is in xml variable.

Upvotes: 3

Views: 2015

Answers (2)

jdweng
jdweng

Reputation: 34419

I use combination of xmlreader and xdocument. Updated code to dynamically get first tag name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            reader.ReadStartElement(); //read root
            XElement.ReadFrom(reader);// read \n
            XElement record = null;
            string recordName = "";
            Boolean first = true;
            while (!reader.EOF)
            {
                if (first)
                {
                    record = (XElement)XElement.ReadFrom(reader);
                    first = false;
                    recordName = record.Name.LocalName;
                }
                else
                {
                    if (reader.Name != recordName)
                    {
                        reader.ReadToFollowing(recordName);
                    }
                    if (!reader.EOF)
                    {
                        record = (XElement)XElement.ReadFrom(reader);
                    }
                }
            }
        }
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500913

No, XDocument loads the whole document into memory. Whether it's "safe" to do this or not depends on what size of document you need to be able to handle.

If you need to handle XML files that wouldn't fit into memory, you'd want to use XmlReader, which is unfortunately considerably harder to use.

Upvotes: 4

Related Questions