Monday, December 05, 2011

LINQ To XML Tips


Use XElement instead of XDocument in LINQ to XML

I misunderstood that it is usually the XElement that is all I needed and not XDocument to work with LINQ to XML.

XElement has just about everything you need and also LINQ works mainly with XElement.

For example, the following code can locate all the "top level" nodes titled page. Within each of the element you can actually find the element titled "regex" no matter how deeply inside that elemenet's tree. This is because I am grabbing all descendant level nodes.


       public void Test(XElement FinderSpec)
        {

            var pages = from f in FinderSpec.Descendants()
                    where f.Name == "page"
                    select f;

            foreach (var i in pages)
            {
                var reg = from tre in i.Descendants()
                          where tre.Name == "regex"
                          select tre;

                foreach (var re in reg)
                {
                    var rs = re.Value;
                }
            }

        }


The XElement class also has handy Load and Save from file as well.

var el = Xelement.Load("test.xml");
el.Save("test2.xml");













No comments: