Reading an xml file is something that every developer has to do at some point (if not regularly). XML protocol is extremely prevalent across all technologies which makes it important to understand how to parse it. Sivlerlight exposes System.XML.Linq namespace that has all the needed classes to use Linq to query your XML to get the node/s that you need.
Always Starts with the Document
As with every XML reader you start out by creating an instance of the document and then filling it with the XML file’s data. In this case Silverlight provides ‘XDocument’ class to instantiate the document object and then the ‘Load’ method to read the data into the object. Then once we’ve loaded the object with data then we can run a traditional Linq query on the data.
Test Case
So lets run through a test case. Lets say we have a configuration file in which we want to determine what logo to display based on the url that called it. So here is our example xml:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <Logos> <Logo url="url1"> <LoginWindowLogo>/namespace;path/img1.png</LoginWindowLogo> </Logo> <Logo url="url2"> <LoginWindowLogo>/namespace;path/img2.png</LoginWindowLogo> </Logo> </Logos> </configuration>
And here is the C# code to read it:
XDocument document = XDocument.Load("Config.xml"); var images = (from e in document.Descendants("Logo") where e.Attribute("url").Value == App.Current.Host.Source.Host select new { LoginWindowLogo = e.Element("LoginWindowLogo").Value, }).FirstOrDefault(); if (images != null) { loginwindowlogopath = images.LoginWindowLogo; }
App.Current.Host.Source.Host is the property that gives you the current apps domain, the function ‘FirstOrDefault’ get the results and turn it into an object that just has the properties selected.
