vendredi 15 février 2013

Windows 8 : Open a local file and read Xml content

Thanks to this tutorial you will learn how to open an Xml File located in you Solution Explorer and how to retrieve value.

We will use Linq on Xml file so you have to add the following  librairies to your projet :


using System.Xml.Linq;
using Windows.Data.Xml.Dom;
using Windows.Storage;


Add a folder named 'Data' for exemple into you Windows Store solution and add the following Xml content into the file 'Schools.xml':

<?xml version="1.0" encoding="utf-8" ?>
<school>
  <name>IUT Toulouse</name>
  <type>Public</type>
  <location>
    <X>45.1</X>
    <Y>32.5</Y>
  </location>
</school>

And into a EventHandler or in the Page_Load for example add the folowing code :

Windows.Storage.StorageFolder storageFolder =await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data"); StorageFile storageFile =await storageFolder.GetFileAsync("Schools.xml"); IAsyncOperation<IRandomAccessStream> stream = await storageFile.OpenAsync(FileAccessMode.Read); XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(storageFile); XDocument doc = XDocument.Parse(xmlDoc.GetXml()); string name = from schools in doc.Descendants("name") select schools.Value;string type = from schools in doc.Descendants("type") select schools.Value;

At the end of the code the variables  name and type contains the value retrieve in the xml file.





Aucun commentaire :

Enregistrer un commentaire