In this recipe let's try to open an XML file saved in the local application folder. We will make use of the XDocument parse method for opening the XML file. LINQ to XML is the best and the easiest way to navigate the XML for Silverlight applications. LINQ to XML replaced the XSLT transformation in C#.
For this recipe let's create a new project named Recipe1_LinqToXml
under the solution folder named Ch3_Recipes
. We will use this solution for all our samples in this chapter. Change the Application Name in the MainPage.xaml
to LINQToXML
. Press F5 and run to make sure you have no errors.
In the following steps we will create an XML file with sample data for our testing purposes and then we will load the results of the LINQ to SQL query into a list box control to be displayed on the screen.
MainPage.xaml.cs
file and add the assembly reference for accessing isolated storage, which is System.IO.IsolatedStorage
. As we are going to use XML and LINQ, we will first add the references to System.Xml
and System.Xml.Linq
in the project and then include the XML and LINQ namespace using declaratives as shown in the following code snippet:using System.IO.IsolatedStorage; using System.Xml; using System.Xml.Linq;
Ch2_MyTasks
recipe sample, let's copy or include DataClass.cs
. Make sure to change the namespace to Recipe1_LinqToXml
. XML
file with sample data and call it MyTasks.xml
, as follows:<?xmlversion="1.0"encoding="utf-8" ?> <tasks> <taskname="name 1" notes="notes 1" priority="Low" datedue="03/01/2011" datecreated="02/01/2011"/> <taskname="name 2" notes="notes 2" priority="High" datedue="04/01/2011" datecreated="02/01/2011"/> <taskname="name 3" notes="notes 3" priority="Medium" datedue="05/01/2011" datecreated="02/01/2011"/> </tasks>
MyTasks.xml
, and in the Properties make sure Build Action is set to Content and Copy to Output is set to Copy if newer as shown in the following screenshot: MainPage.xaml.cs
file. Add a new method named parseXMLUsingLinq
with a string parameter passedXmlFileName
to open the file from the local folder and parse the XML file:private void parseXMLUsingLinq(stringpassedXmlFileName) { XDocumentxdoc = XDocument.Load(passedXmlFileName); IEnumerable<DataClass>iTasks; iTasks = from task inxdoc.Descendants("task") select new DataClass { Name = (string)task.Attribute("name"), Notes = (string)task.Attribute("notes"), Priority = (string)task.Attribute("priority"), DateDue = (DateTime)task.Attribute("datedue"), DateCreated = (DateTime)task.Attribute("datecreated") }; lstTasks.ItemsSource = iTasks; }
MainPage_Loaded
event method and call the parseXMLUsingLinq
method passing the name of the XML file we created:private void MainPage_Loaded(object sender, RoutedEventArgs e) { parseXMLUsingLinq("MyTasks.xml"); }
In this recipe we opened the XML file from the local storage using the parse method of the XDocument
class and bound it to the list box control. We initially loaded the XML content into XDocument
and used the LINQ statement to get all the task elements.
In this recipe we learned how to open a local XML file. We can learn more in the following section using the XmlReader
instead of LINQ to XML. Also, refer to the following MSDN article to learn more on the subject of LINQ to SQL: http://msdn.microsoft.com/en-us/library/bb425822.aspx
Now let's try parsing the same XML using the XmlReader
. Add a new project to the previous solution Ch3_Recipes
and call it Recipe2_XmlReader
. Copy the DataClass.cs
and MyTasks.xml
files from the previous recipe and add them to the project. Change the Namespace in the DataClass.cs
file and run it to make sure everything compiles successfully.
MainPage.xaml.cs
file and add another method called parseXMLUsingReader
with parameter StringpassedXmlFileName
.private void parseXMLUsingReader(stringReaderpassedXmlFileName) { XmlReaderrdr=XmlReader.Create(passedXmlContent); while (rdr.Read()) { if (rdr.NodeType == XmlNodeType.Element) { if (rdr.Name == "task") { DataClass task = new DataClass { Name = rdr["name"], Notes = rdr["notes"], Priority = rdr["priority"], DateCreated = Convert.ToDateTime(rdr["datecreated"]), DateDue= Convert.ToDateTime(rdr["datedue"]) }; } } }
MainPage_Loaded
event in the MainPage.xaml
file at the last line as Loaded="MainPage_Loaded
", as shown in the following code snippet:<phone:PhoneApplicationPage
x:Class="Recipe2_XmlReader.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml xmlns:phone="clr-namespace:Microsoft.Phone.Controls;
assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;
assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResourcePhoneFontFamilyNormal}"
FontSize="{StaticResourcePhoneFontSizeNormal}"
Foreground="{StaticResourcePhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" Loaded="MainPage_Loaded">
MainPage_Loaded
event method call parseXMLUsingReader
with "MyTasks.xml
" as the parameter:private void MainPage_Loaded(object sender, RoutedEventArgs e) { parseXMLUsingReader("MyTasks.xml"); }