Xml and Linq in Silverlight

While answering a post in silverlight.net froum, I am surprised that the Silverlight work so well with XML WebService. 

First, in Xml WebService, you usually pass the Xml String to the Silverlight Application or using Http.Request to get the string by the Application itself. Silverlight can also parse it however you get it.

Now, I am going to introduce a good way to use the Linq with Silverlight.

Assume, you get a string by Xml Service after the Async Completed. That is,

<Records>
    <UserRecords>
        <Name>Steve</Name>
        <Age>17</Age>
        <Occupation>Student</Occupation>
        <Birthday>18-11-1990</Birthday>
    </UserRecords>
    <UserRecords>
        <Name>Hazel</Name>
        <Age>17</Age>
        <Occupation>Student</Occupation>
        <Birthday>14-12-1990</Birthday>
    </UserRecords>
    ...
    ...
    ...
</Records>

 

And Suppose there is so many records here. It is very complicated for you to use XmlReader
Now, XDocument is introduced.

string[,] mydata = new string[100,4]

if (e.Error == null)
{
    int i = -1;
    XDocument xd = XDocument.Parse(e.Result);
    var v = from g in xd.Descendants("UserRecords" )
    select new 
            {
                uname = g.Element("Name").Value,
                uage = g.Element("Age").Value,
                uocc = g.Element("Occupation").Value,
                udob = g.Element("Birthday").Value,
            }; 
    foreach (var itm in v)
    {
        i++;
        mydata[i,0] = itm.uname.Trim();
        mydata[i,1] = itm.uage.Trim();
        mydata[i,2] = itm.uocc.Trim();
        mydata[i,3] = itm.udob.Trim();
    }
} 

Furthermore, if the data is not present in this way, is as follow,

<Ranks>
  <Rank place="1">
    <FIELD NAME="name">Steve</FIELD>
    <FIELD NAME="age">17</FIELD>
  </Rank>
  <Rank place="2">
    <FIELD NAME="name">Hazel</FIELD>
    <FIELD NAME="age">17</FIELD>
  </Rank>
<Ranks>

The way in parsing this in similar.

public class RankingList
{
public string name {get ; set; }
public string age {get ; set; }
}
if (e.Error == null)
{
            List list = new List();
            XDocument xd = XDocument.Parse(e.Result);
            var v = from row in xd.Descendants("Rank")
                    select row.Elements("FIELD").ToDictionary(r=>r.Attribute("name").Value, r=>r.Value);
            foreach (var itm in v)
            {
                    RankingList t = new RankingList();
                    t.name = itm["Name"];
                    t.age = itm["Age"];
                    list.Add(t);
            }
}

 

I hope everyone can familiar with this Linq and Xml in Silverlight.

Live with Light.

Steve Wong (Hong Kong)