Read XML File In Windows 10 Universal App

To load local HTML files in Windows 10 universal app, we need to read and display the data from local XML file sometimes in our apps. Here I will explain how to read local XML files in Windows 10 app.

Let’s see the steps:

Create new Windows 10 app and add the XML file that you want to read, here I add the following xml file to load the student’s details.

Use encoding="utf-8", otherwise you will probably face an exception.

Next create a sample data class used to store the XML element values like the following code.
  1. public class Person  
  2. {  
  3. string name;  
  4. int age;  
  6. public string Name  
  7. {  
  8. get { return name; }  
  9. set { name = value; }  
  10. }  
  11. public int Age  
  12. {  
  13. get { return age; }  
  14. set { age = value; }  
  15. }  
  16. }  
Add ListBox control to list the student details from xml file.
  1. <ListBox x:Name="StudentlistBox" HorizontalAlignment="Left" Height="562" Margin="10,10,0,0" VerticalAlignment="Top" Width="340">  
  2. <ListBox.ItemTemplate>  
  3. <DataTemplate>  
  4. <StackPanel Margin="10" >  
  5. <TextBlock Text="{Binding Name}"/>  
  6. <TextBlock Text="{Binding Age}"/>  
  7. </StackPanel>  
  8. </DataTemplate>  
  9. </ListBox.ItemTemplate>  
  10. </ListBox>  
Here, I am binding the name and age in the listbox.

Now read the xml file and assign the data to listbox using the following code.
  1. string XMLFilePath = Path.Combine(Package.Current.InstalledLocation.Path, "SampleXMLFile.xml");  
  2. XDocument loadedData = XDocument.Load(XMLFilePath);  
  1. var data = from query in loadedData.Descendants("person")  
  2. select new Person  
  3. {  
  4. Name = (string)query.Element("name"),  
  5. Age = (int)query.Element("age")  
  6. };  
  7. StudentlistBox.ItemsSource = data;  
To read the date from the XML files you need to use XDocument. To do that we need to include the namespace “using System.Xml.Linq”.

Now run the app and see the excepted output looks like the following screen.

Source Code

For more information on Windows 10 UWP, refer to my e-book:
Read more articles on Universal Windows Platform:

Up Next
    Ebook Download
    View all
    View all