Monday, March 12, 2012

[Csharp] Linq To XML first sample

Use .NET 3.5 or 4.0, you see a powerful LINQ. For study LINQ I have some links in MSDN are very useful.
 - Linq to Object
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
 - Linq to XML
http://msdn.microsoft.com/en-us/vstudio/bb688087
 - And Linq to SQL
http://msdn.microsoft.com/en-us/vstudio/bb688085

Today, I write a first sample of me to use Linq to XML. I hope you enjoy it :)


   1:  namespace LinqToXmlSample
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {
   7:              const string myXml = 
   8:  @"<Root>
   9:      <ChildCollection>
  10:          <Child>Data1</Child>
  11:          <Child>Data2</Child>
  12:          <Child>Data3</Child>
  13:          <Child>Data4</Child>
  14:      </ChildCollection>
  15:  </Root>";
  16:   
  17:              XDocument document = XDocument.Parse(myXml);
  18:   
  19:              var children = from child in document.Element("Root").Element("ChildCollection").Descendants("Child") select  child;
  20:   
  21:              foreach (var child in children)
  22:              {
  23:                  Console.WriteLine(child.Value);
  24:              }
  25:   
  26:              Console.ReadKey();
  27:          }
  28:      }
  29:  }

I think it's very easy to understand.

No comments:

Post a Comment