michielpost.nl

Read XML from your project in Windows 8 / WinRT

08-04-2012

This blog post is about Windows 8 / WinRT XAML apps. It's based on the Windows 8 Consumer Preview, things can still change in upcoming versions.

How to read an XML file that is included in your Visual Studio project in a Windows 8 / WinRT project?

A common scenario is to have some default data, like a list of locations, in XML format. You want to ship this XML with your application and read from it.

How do you read from the XML file that is included in the project?

First: Include the XML in your project.
Make sure the Build Action is set to Content and the Copy to output directory is set to "Copy if newer".

Second: Read from the XML:
Use this code sample to read from your XML file

var sf = await Package.Current.InstalledLocation.GetFileAsync(@"somedirectory\mydata.xml");
var file = await sf.OpenAsync(FileAccessMode.Read);
Stream inStream = file.AsStreamForRead();

XElement myFirstXmlElement = XDocument.Load(inStream).Elements().First();

The methods used here are async, so you should put async in your method definition.

Hope this helps! Took me a lot of time to figure out :)

Comments


Viktor 18-04-2012
Thanks, saved me a headbang or two :).


Omar 03-08-2012
Thanks for the tip regards Omar


New Comment

Name
E-mail (not published)
Comment
Enter the code shown: