Linq to Xml: Is XDocument a cache reader?

I like the Linq to Xml API. The simplest one I've ever used.

I also remembered that it was implemented on top XmlReader, which is a non-cache reader, which means:

var rdr = XmlReader.Create("path/to/huge_3Gb.xml");

... will return immediately (perhaps by reading, at best, the xml header).

The documentation for XDocument.Load()indicates what it uses XmlReader.Create().

I expected, as with all Linq, that I would get lazy behavior when executing Linq2Xml.
But then I tried this, as usual, for everything regarding files:

using(var xdoc = XDocument.Load("file")){ ... }

and surprise! It does not compile because XDocument does NOT implement IDisposable!

Hmm, this is weird! How can I free a file descriptor when I finished using XDocument?

And then it dawned on me: perhaps it XDocument.Load()eats up all the Xml in memory at once (and closes the file descriptor immediately)?

So I tried:

var xdoc = XDocument.Load("path/to/huge_3Gb.xml");

and waited and waited, and then the process said:

Unhandled Exception: OutOfMemoryException.

So, Linq to Xml is close to perfection (awesome API), but no cigar (when used on large Xmls).

</rant>

My questions:

  • Am I missing something and is there a way to use Linq for Xml lazily?

  • If the answer to the previous question is "No":

Is there an objective reason why the Linq to Xml API cannot have lazy behavior similar to, say, Linq for objects? It seems to me that at least some operations (for example, things that are possible using direct only XmlReader) can be implemented lazily.

... , ,

", , , , ​​ "?

+4
1

Linq to Xml . , . , , - , . Linq to xml XML xml (.. ).

, , Linq Xml. XDocument, :

<movies>
  <movie id="1" name="Avatar"/>
  <movie id="2" name="Doctor Who"/>
</movies>

, XML- . .

 var xdoc = XDocument.Parse(xml_string);
 // or XDocument.Load(file_name);
 // or new XDocument(new XElement("movies"), ...)

:

var query = xdoc.Descendants("movie");

xml , :

xdoc.Root.Add(new XElement("movie"), new XAttribute("id", 3));

:

int moviesCount = query.Count(); // returns 3

, Linq to Xml , Linq Data-in-memory, .

: XDocument IDisposable, .

+6

All Articles