Reading XML in Silverlight

This post will tell you the easy way to read xml in silverlight.

In the last article we saw how to create XML. Now take my words, that was all you need. It takes a hell lot a deal to create XML, but when we talk about reading it, it all goes like rather easy and simple. Even I once taught my aunt how to do it, while a matter of fact is that she never sat with me again after she saw what I was doing. Remember our last XML?

<?xml version="1.0" encoding="UTF-8" ?>

<Main>

  <SubMain>

    <Hello>Neelma</Hello>

  </SubMain>

</Main>

Now just try to embrace the beauty of the code when we try to read the value written inside the XML tags. For example, if we want to read the name written inside the tag "Hello", we write it simply as:

private void SetPropertyAsPerXML(string xml)

{

var propertyXml = XElement.Parse(xml);

var node = propertyXml.Descendants("Hello").FirstOrDefault();

var nodeValue = node.Value;

}

The function Descendants will take the Name of the tag or node and in turn will return the IEnumerable collection of XElements in the XML having that Node name. Simply put, you can find any node, you just need to pass the name of that node and boom, here comes the collection.
Nevertheless, you need not iterate through all the collection to find the value of the node meeting your requirements, you can use the power of LinQ instead, let me show you how. Imagine I have an XML like this.

<?xml version="1.0" encoding="UTF-8" ?>

<Main>

  <SubMain>

    <Hello>Paridhi</Hello>

    <Hello>Neelma</Hello>

    <Hello>Himani</Hello>

  </SubMain>

</Main>

Now as you can see, I am stuck with the name of 3 girls in my XML. Would I go finding the Node containing the name of my favorite girl in case the list goes bizerk and clumpy, which in fact, is rather not an impossible scenario, it will take a loop or two, to get it. Why not instead just use Linq? Here is what I can do.

private void SetPropertyAsPerXML(string xml)

{

var propertyXml = XElement.Parse(xml);

var node = propertyXml.Descendants("Hello").FirstOrDefault(x=>x.Value == "Neelma");

var nodeValue = node.Value;

}

So, with the beauty of parsing and the power of LinQ, reading XML is no longer a pain in the brain, or you might have guessed it already; yes you are right.