Skip to content

Instantly share code, notes, and snippets.

@erdomke
Created December 16, 2016 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erdomke/633b7e352107fb61fbd3d84b8cc24891 to your computer and use it in GitHub Desktop.
Save erdomke/633b7e352107fb61fbd3d84b8cc24891 to your computer and use it in GitHub Desktop.
Correct streaming of XElements
// The code posted at https://blogs.msdn.microsoft.com/xmlteam/2007/03/24/streaming-with-linq-to-xml-part-2/
// will skip every other element with compressed XML. This occurs because the reader after ReadFrom
// is already positioned on the next node and then the reader.Read() will move it to the node afterwards.
// The logic in this snippet fixes the problem.
internal static IEnumerable<XElement> StreamElements(Stream stream, XName matchName)
{
using (var reader = XmlReader.Create(stream))
{
reader.MoveToContent();
var continueNoRead = false;
while (continueNoRead || reader.Read())
{
continueNoRead = false;
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.LocalName == matchName.LocalName
&& ((string.IsNullOrEmpty(reader.NamespaceURI) && string.IsNullOrEmpty(matchName.NamespaceName))
|| reader.NamespaceURI == matchName.NamespaceName))
{
var el = XElement.ReadFrom(reader) as XElement;
if (el != null)
yield return el;
continueNoRead = true;
}
break;
}
}
reader.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment