Mega Code Archive

 
Categories / C# / XML LINQ
 

Query Xml document by node type with Linq

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;         int whiteSpaceNodes;         sr = new StringReader("<Root> <Child> </Child> </Root>");         XDocument xmlTree2 = XDocument.Load(sr, LoadOptions.PreserveWhitespace);         sr.Close();         whiteSpaceNodes = xmlTree2             .Element("Root")             .DescendantNodesAndSelf()             .OfType<XText>()             .Where(tNode => tNode.ToString().Trim().Length == 0)             .Count();         Console.WriteLine(whiteSpaceNodes);     } }