Richard Blewett reminded me that the XmlReader.ReadSubtree method makes it even easier to use LINQ to XML with a streaming approach. The code sample below will load nodes from an arbitrary XML files and yield them to the caller as they’re read from file:
static IEnumerable<XElement> Load(string filename, string elementName)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (XmlReader reader = XmlReader.Create(filename, settings))
{
while (reader.ReadToFollowing(elementName))
{
// build element from subtree
XElement element = XElement.Load(reader.ReadSubtree());
yield return element;
}
}
}