views:

359

answers:

2

Hi,

Can anyone please guide me on how to use XElement in Silverlight (C#) to read an XML file.

Thank You!

A: 

Here's some example code:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    DataGrid1.ItemsSource = GetStatusReport();
}

public List<Status> GetStatusReport()
{
    List<Status> statusReport = new List<Status>();

    XElement doc = XElement.Load(@"Data/StatusReport.xml");

    statusReport = (from el in doc.Elements()
                    select GetStatus(el)).ToList();

    return statusReport;
}

private Status GetStatus(XElement el)
{
    Status s = new Status();
    s.Description = el.Attribute("Description").Value;
    s.Date = DateTime.Parse(el.Attribute("Date").Value);
    return s;
}
Peter McGrattan
Hi, intellisense cannot find any method Load or Parse for XElement!Do I need to import any libraries apart from System.Linq?
James
You need to reference the System.Xml.Linq assembly then add `using System.Xml.Linq` in C#
Peter McGrattan
I added a reference to System.Xml.Linq! however, I cannot add "using System.Xml.Linq" it gives me the error, "missing assembly". When I see the references of my project, I can see a reference to System.Xml.Linq tho!
James
+1  A: 

Hi there,

you can use the static XElement.Load method to load XML e.g. from a file stream or directly from an XML file packaged into the .XAP.

Here's an example: link text

The MSDN page on XElement might also be helpful (Google: silverlight XElement class).

Cheers, Alex

alexander.biskop