Monday, March 22, 2010

Read xml from web page and bind the data to Silverlight module

Read xml from web page and bind the data to Silverlight module.

we are discussing about the code we need to place in Page.xaml.cs file to read xml from web page.

here we build an architecture that SharePoint will build the XML for us and write it on the page and Silverlight grabs the XML from the page and displays the images on the UI

we need to place in Page.xaml.cs file to read xml from web page.


    public Page()  
   {  
   string controlid = "divImgs"; //You can also use intiparams of Silverlight params to get the id.  
   InitializeComponent();  
    
   string xmlstring = string.Empty;  
    if (controlid != null)  
  {  
   HtmlElement ctl = HtmlPage.Document.GetElementById(controlid);  
  if (ctl != null)  
  xmlstring = (string)ctl.GetProperty("innerHTML");  
   }  
     
   if (!string.IsNullOrEmpty(xmlstring))  
   {  
   ProcessXML(xmlstring);  
   }  
   }  


we need to process the XML and bind the data to the silverlight control. This is why i am calling a function called "Process XML".

Code For that process
   private void ProcessXML(string xml)  
    {  
    images = new List();  
    if (xml != string.Empty)  
    {  
 try  
    {  
    StringReader textStream = null;  
    textStream = new StringReader(xml);  
     
  if (textStream != null)  
   {  
  using (XmlReader reader = XmlReader.Create(textStream))  
   {  
   while (!reader.EOF)  
   {  
   if ((reader.IsStartElement()) && (reader.LocalName == "slides"))  
   {  
   if (reader.HasAttributes)  
   {  
   reader.MoveToAttribute("baseUrl");  
   }  
   }  
   else  
   {  
   if ((reader.LocalName == "slide") && (reader.HasAttributes))  
   {  
   reader.MoveToAttribute("imageUrl");  
   string imageName = reader.Value.ToLower();  
   if ((imageName.Contains(".jpg")  
    imageName.Contains(".png")))  
   images.Add(reader.Value);  
   }  
     
  }  
 reader.Read();  
 }  
 }  
  }  
   }  
  catch (Exception ex)  
   {  
  }  
  }  
  }