In the last post, we had seen how to create XML. Now take my words, that was all you need. It takes a hell lot of 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 that’s the matter of fact she had never seated before me again when she saw that I am working. Remember our last XML.
1: <?xml version="1.0" encoding="UTF-8" ?>
2: <Main>
3: <SubMain>
4: <Hello>Neelma</Hello>
5: </SubMain>
6: </Main>
Now just try to embrace the beauty of the code when we try to read the value written inside any of the XML tag. For example, if we want to read the name written inside the tag Hello, we write simply as,
1: private void SetPropertyAsPerXML(string xml)
2: {
3: var propertyXml = XElement.Parse(xml);
4: var node = propertyXml.Descendants("Hello").FirstOrDefault();
5: var nodeValue = node.Value;
6: }
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 to iterate through all the collection to find the value of the node meeting your requirment, you can use the power of Linq instead, let me show you. Imagine I have an XML like this.
1: <?xml version="1.0" encoding="UTF-8" ?>
2: <Main>
3: <SubMain>
4: <Hello>Paridhi</Hello>
5: <Hello>Neelma</Hello>
6: <Hello>Himani</Hello>
7: </SubMain>
8: </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 go bizerk and clumpy, which in fact, is rather not an impossible scenario, it will take a loop or two, to get it. Why instead I rather not just use Linq? Here is what I can do.
1: private void SetPropertyAsPerXML(string xml)
2: {
3: var propertyXml = XElement.Parse(xml);
4: var node = propertyXml.Descendants("Hello").FirstOrDefault(x=>x.Value == "Neelma");
5: var nodeValue = node.Value;
6: }
So, with the beauty of parsing and power of Linq, reading XML is no longer pain in the brain, or you might have guessed it already; yes you are right.
0 comments