Mega Code Archive

 
Categories / C# / XML LINQ
 

XElement Load Method (TextReader, LoadOptions) loads an XElement from a TextReader

using System; using System.IO; using System.Linq; using System.Xml.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {     public static void Main()     {         TextReader sr = new StringReader("<Root> <Child> </Child> </Root>");         XElement xmlTree1 = XElement.Load(sr, LoadOptions.None);         sr.Close();         int whiteSpaceNodes = xmlTree1             .DescendantNodesAndSelf()             .OfType<XText>()             .Where(tNode => tNode.ToString().Trim().Length == 0)             .Count();         Console.WriteLine("Count of white space nodes (not preserving whitespace): {0}", whiteSpaceNodes);         sr = new StringReader("<Root> <Child> </Child> </Root>");         XElement xmlTree2 = XElement.Load(sr, LoadOptions.PreserveWhitespace);         sr.Close();         whiteSpaceNodes = xmlTree2             .DescendantNodesAndSelf()             .OfType<XText>()             .Where(tNode => tNode.ToString().Trim().Length == 0)             .Count();         Console.WriteLine("Count of white space nodes (preserving whitespace): {0}", whiteSpaceNodes);     } }