Read More Ninja Action!

LINQ - Object from XML in seconds

I'm not going to pretend that this is some amazing discovery or anything...but I was excited when I wrote it, so now you get to see it too!

Basically using just a bit of LINQ syntax, I'm iterating through an XML document and converting it directly into my custom object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Reflection;

namespace MyBaddassCodeBase.NinjaCampRox
{
 public class Ninja
 {
  public int SwordsInHand { get; set; }

  public Ninja()
  {
     
  }

  public static IEnumerable CreateFromXML(string xmlData)
  {
   XDocument xData = XDocument.Parse(xmlData);

   var ninjas = from swordNode in xData.Descendants("Swords")
         select new
         {
          Swords = swordNode.Value
         };

   foreach (var ninja in ninjas)
   {
    Ninja nja = new Ninja();
    nja.SwordsInHand = ninja.Swords;
    yield return nja;
   }
  }
 }  
}

One I have that, I can quickly build and iterate through enumerable lists of that custom object.

Neat isn't it?