views:

25

answers:

1

I'm completely new at silverlight, and trying to do things "the right way".

Problem is: I have an XML that I need to get from a web server, and I need to display that data in a datagrid.

I've searched around and I've managed to get the following:

say my XML looks like:

<customers>
    <customer>
        <name>A Person</name>
        <address>my address</address>
    </customer>
    <customer>
        <name>A Guy</name>
        <address>my address 2</address>
    </customer>
</customers>

I can retrieve this and populate a POCO such as:

public class Customer
{
    public string Name { get; set; }

    public string Address { get; set; }
}
...
XDocument oDoc = //read from a string asnychronously
var myData = from info in oDoc.Descendants("customer")
    select new Customer
    {
        Name = Convert.ToString(info.Element("name").Value),
        Address = Convert.ToString(info.Element("address").Value
    };
_grid.ItemsSource = myData;

However, if I take this approach, I won't really be using Silverlight's dynamic binding capabilities.

How can I do this in the "Silverlight" way so that when I (or someone else who actually knows silverlight) look at the code a few years down the line, don't hate absolutely hate what I've done.

+2  A: 

Take a look at using the XMLSerializer.Deserialize method to de-serialize your XML automatically without having to deal with XDocument. Your class will look like this:

[XmlRoot]
public class Customer
{
    [XmlElement]
    public string Name { get; set; }

    [XmlElement]
    public string Address { get; set; }

}

Once you have the data de-serialized, take a look at MVVM on how to properly bind the data to your views.

Murven
+1: For deserialising.
AnthonyWJones
However, doing the above for the Customer class doesn't "automatically" give you an IEnumerable<Customer>.
iggymoran
Yes, of course, there are a couple of steps you have to go through: Create a serializer and pass the source of the data to de-serialize. However, this is a more maintainable way of doing it as adding or removing properties or even entire classes does not require you to update the de-serialization code, just the classes and attributes. I will try to add some more detail to the answer later, to make this clearer.
Murven
I had taken a look at that MVVM how-to, I just missed a few bits that are not really explicit unless you download the full code to ill in the missing parts.Thanks a lot for the pointers anyhow, its good to get knowledge of other things you get "for free".
iggymoran
For anyone interested, Mark Gravell's answer on http://stackoverflow.com/questions/608110/is-it-possible-to-deserialize-xml-into-listt clearly shows how to implement the list of nodes.
iggymoran