Aidan Garnish

Collaboration Not Competition

Simple Linq to XML example

 string xml = "<?xml version='1.0' encoding='utf-8'?><people>"
                + "<person><id>1</id><name>Aidan Garnish</name><company>65hours</company><email>aidan@65hours.com</email></person>"
                + "<person><id>2</id><name>Joe Bloggs</name><company>65hours</company><email>Fred@65hours.com</email></person>"
                + "<person><id>3</id><name>Fred Smith</name><company>Microsoft</company><email>Joe@Microsoft.com</email></person></people>";

           

            XDocument doc = XDocument.Parse(xml);

            //filter by company and return a collection of names as strings
            var query = from person in doc.Descendants("person")
              where (string)person.Element("company") == "65hours"
              select (string)person.Element("name");

            foreach (string name in query)
            {
                Console.WriteLine(name);
            }

 

            //return a collection of objects
            var query2 = from person in doc.Descendants("person")
                    where (string)person.Element("company") == "65hours"
                    select new
                         {
                             id = person.Element("id").Value,
                             name = person.Element("name").Value,
                             email =person.Element("email").Value,
                             company = person.Element("name").Value
                         };
           
            foreach (var obj in query2)
            {
                Console.WriteLine(obj.id + " - " + obj.name);
            }           

            Console.ReadLine();

Add comment

Loading