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,
[sourcecode language='xml']
[/sourcecode]
And Suppose there is so many records here. It is very complicated for you to use XmlReader
Now, XDocument is introduced.
[sourcecode language='csharp']
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();
}
}
[/sourcecode]
Furthermore, if the data is not present in this way, is as follow,
[sourcecode language='xml']
[/sourcecode]
The way in parsing this in similar.
[sourcecode language='csharp']
public class RankingList
{
public string name {get ; set; }
public string age {get ; set; }
}
if (e.Error == null)
{
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);
}
}
[/sourcecode]
I hope everyone can familiar with this Linq and Xml in Silverlight.
Live with Light.
Steve Wong (Hong Kong)







0 comments:
Post a Comment