Created
December 16, 2016 16:08
-
-
Save erdomke/633b7e352107fb61fbd3d84b8cc24891 to your computer and use it in GitHub Desktop.
Correct streaming of XElements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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