Read XML file in WinJS Project using Windows Runtime Component

As we know, WinJS applications are built using HTML/JS/CSS. And for a complete application, we will need async operations like SQL database operations, web-service calls, and other native XML read-write, File read-write which cannot be done directly in WinJS applications.

So we have to use Windows Runtime Component to access native C# methods as discussed in my previous article: WinJS application with Windows Runtime Component to access Native C# Code.

In this article, I will show you how to read XML file using Windows Runtime Component and display its content in HTML page.

Step 1

Firstly, create a WinJS project.

Step 2

We need to do the following things as discussed in my previous article.

  • Add a Windows Runtime Component project and name it ‘WinRuntimes’
  • Delete default class ‘Class1.cs’
  • Add a new class and name it ‘Service’
  • Add WinRuntimes reference in WinJS project
  • Build the project.

Step 3

Let us add an xml file in solution explorer folder. Right click on project and add a new item and select xml file.

file

XML file content

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <AllUsers Account="admin" Number="100" DateTime="20160423_081710">  
  3.     <User>  
  4.         <UserId>105</UserId>  
  5.         <UserName>Kishor</UserName>  
  6.     </User>  
  7. </AllUsers>  
Step 4

In Service class, we have IAsyncOperation for ReadXML() where we read the file from Installed location i.e. Solution Explorer. Here we load the xml file content in the XmlDocument and get the root and its attributes. Also we select the Nodes and its values. Finally, we create a JSON Object and return it as string.

Complete Code for Service class
  1. using Newtonsoft.Json.Linq;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using Windows.ApplicationModel;  
  8. using Windows.Data.Xml.Dom;  
  9. using Windows.Foundation;  
  10. using Windows.Storage;  
  11. namespace WinRuntimes  
  12. {  
  13.     public sealed class Service   
  14.     {  
  15.         public IAsyncOperation < string > ReadXML()   
  16.         {  
  17.             return ReadXMLHelper().AsAsyncOperation();  
  18.         }  
  19.         private async Task < string > ReadXMLHelper()   
  20.         {  
  21.             try {  
  22.                 StorageFile xmlFile = await Package.Current.InstalledLocation.GetFileAsync("test.xml");  
  23.                 string xmlFileContent = await FileIO.ReadTextAsync(xmlFile);  
  24.                 JObject obj = new JObject();  
  25.                 // XML Read Operation  
  26.                 XmlDocument doc = new XmlDocument();  
  27.                 doc.LoadXml(xmlFileContent);  
  28.                 XmlElement root = doc.DocumentElement;  
  29.                 string account = root.GetAttribute("Account");  
  30.                 string number = root.GetAttribute("Number");  
  31.                 string dateTime = root.GetAttribute("DateTime");  
  32.                 XmlNodeList nodes = root.SelectNodes("User");  
  33.                 foreach(XmlElement item in nodes) {  
  34.                     var UserId = item.SelectNodes("UserId")[0].InnerText;  
  35.                     var UserName = item.SelectNodes("UserName")[0].InnerText;  
  36.                     obj.Add("UserId", UserId);  
  37.                     obj.Add("UserName", UserName);  
  38.                 }  
  39.                 return obj.ToString();  
  40.             } catch (Exception ex)   
  41.             {  
  42.                 return "";  
  43.             }  
  44.         }  
  45.     }  
  46. }  
Step 5

Add a script.js file and reference it in default.html:

Now in default.html, lets add the following things:
  • Button with click event to read xml file
  • Two input fields to show the xml contents.

Complete html code snippet for default.html is,

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <meta charset="utf-8" />  
  6.     <title>WinJS_XML</title>  
  7.     <!-- WinJS references -->  
  8.     <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />  
  9.     <script src="//Microsoft.WinJS.2.0/js/base.js"></script>  
  10.     <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>  
  11.     <!-- WinJS_XML references -->  
  12.     <link href="/css/default.css" rel="stylesheet" />  
  13.     <script src="/js/default.js"></script>  
  14.     <script src="js/script.js"></script>  
  15. </head>  
  16.   
  17. <body>  
  18.     <p>WinJS XML operaions</p> <button onclick="readXML()">Read XML file</button> <input id="userId" /> <input id="userName" /> </body>  
  19.   
  20. </html>  
Step 6

In script.js, we create a service object of Service class and call the readXML function. Here we have used the function to achieve asynchronous programming.

We parse the xml content that is obtained from native C# part and display it in our html.

Complete code snippet for script.js is,
  1. var service = new WinRuntimes.Service();  
  2.   
  3. function readXML()   
  4. {  
  5.     service.readXML().then(function(xmlContent)  
  6.     {  
  7.         var jObj = JSON.parse(xmlContent);  
  8.         document.getElementById("userId").value = jObj.UserId;  
  9.         document.getElementById("userName").value = jObj.UserName;  
  10.     });  
  11. }  
Step 7

Run the application and click on Read XML file button. You will see the values in the input fields that are read from the XML file.

xml file

Complete project in GitHub.

Up Next
    Ebook Download
    View all
    Learn
    View all