Wednesday, October 20, 2010

Reading XML through LINQ with Silverlight

Let's start with a simple xml file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ImageDataSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ImageData>
    <Index>30001</Index>
    <Name>icon1</Name>
    <Left>6</Left>
    <Top>4</Top>
    <Width>13</Width>
    <Height>5</Height>
  </ImageData>
  <ImageData>
    <Index>30002</Index>
    <Name>icon2</Name>
    <Left>6</Left>
    <Top>11</Top>
    <Width>13</Width>
    <Height>5</Height>
  </ImageData>
</ImageDataSet>

And an entity class
 
public class ImageData
{
   public int Index { getset; }
   public string Name { getset; }
   public double Left { getset; }
   public double Top { getset; }
   public double Width { getset; }
   public double Height { getset; }
}
 
Now we read the xml content by using this function

public static List<T> ReadXml<T>(Stream stream) where T : new()
{
    List<T> ts = new List<T>();
 
    Type type = typeof(T);
    PropertyInfo[] infos = type.GetProperties();
    XDocument xDoc = XDocument.Load(stream);
 
    var root = xDoc.Root;
    if (root != null)
    {
        foreach (XElement element in root.Elements(type.Name))
        {
         T t = new T();
         foreach (PropertyInfo propertyInfo in infos)
         {
             var ele = element.Element(propertyInfo.Name);
             if(ele != null)
             {
                 try
                 {
                    propertyInfo.SetValue(t, Convert.ChangeType(ele.Value, propertyInfo.PropertyType , null), null);
                 }
                 catch (Exception)
                 {
                        //type is not appropriate
                  }
               }
            }
            ts.Add(t);
        }
    }
    return ts;
}

The input stream can be getting by using Embedded Resources. In my sample ResourceData is a class in the same namespace.

Assembly assembly = typeof(ResourceData).Assembly;
Stream imageDataStream = assembly.GetManifestResourceStream(typeof(ResourceData), 
                          "Image1.xml");

var imageData = XmlHelper.ReadXml<ImageData>(imageDataStream);

J

No comments:

Post a Comment