Loading an XML file in your Silverlight project into memory

Version : Silverlight 2 Beta 2

Reading an XML file in an XAP package can easily be done with the help of a helper class like so:

   1: public static class XmlHelper
   2: {
   3:     public static XElement LoadDocument(string fileName)
   4:     {
   5:         //No longer required in Silverlight 2 since
   6:         //XmlXapResolver has been added as the default resolver for XmlReader
   7:         //ref: http://msdn.microsoft.com/en-us/library/cc189007(vs.95).aspx
   8:         //XmlReaderSettings settings = new XmlReaderSettings();
   9:         //settings.XmlResolver = new XmlXapResolver();
  10:         //XmlReader reader = XmlReader.Create(fileName, settings);
  11:  
  12:         XmlReader reader = XmlReader.Create(fileName);
  13:         XElement element = XElement.Load(reader);
  14:         return element;
  15:     }
  16: }

Once you have the XElement object, you are free to manipulate it with LINQ to XML as shown below:

   1: public static List<Slide> LoadSlides()
   2: {
   3:     XElement element = XmlHelper.LoadDocument("Slides.xml");
   4:     var slides = from slide in element.Descendants("Slide")
   5:                  select new Slide {
   6:                     Title = (string)slide.Element("Title"),
   7:                     Text = (string)slide.Element("Text"),
   8:                     Image = (string)slide.Element("Image"),
   9:                  };
  10:     return slides.ToList();
  11: }

The method above returns a List<Slide> where the Slide class is defined like so:

   1: public class Slide
   2: {
   3:     public string Title { get; set; }
   4:     public string Text { get; set; }
   5:     public string Image { get; set; }
   6: }

and the contents of the XML file we are reading is:

   1: <?xml version="1.0" encoding="utf-8"?>
   2: <Slides>
   3:   <Slide>
   4:     <Title>Slide 1</Title>
   5:     <Text>Slide 1 Description</Text>
   6:     <Image>Slide1.jpg</Image>
   7:   </Slide>
   8:   <Slide>
   9:     <Title>Slide 2</Title>
  10:     <Text>Slide 2 Description</Text>
  11:     <Image>Slide2.jpg</Image>
  12:   </Slide>
  13: </Slides>

Note that the XML file should have its BuildAction set to "Content".

3 Comments

Comments have been disabled for this content.