Florian Rousselet

Passionné de Windows Phone

[WP7] Use your own XML in a WP7 app

Use your own XML in a WP7 app

Hi,

Today I will present you, How to Use your own XML in a WP7 app .

Sometimes, you have a few static ressources that you want to put inside your app. I will show you with a list of Game of Thrones houses ( My App ) how to do that.

The XML

First, you need to format your data correctly in XML.

For example :

<Houses>
<House>
<Id>0</Id>
<Name>House Arryn</Name>
<LDescription>House Arryn is one of the Great Houses of Westeros. It has ruled over the Vale of Arryn for millennia, originally as the Kings of Mountain and Vale and more recently as Lords of the Vale and Wardens of the East under the Targaryen kings and King Robert Baratheon.House Arryn's sigil is a white moon and falcon on a sky-blue field. Their motto is "As High As Honor". </LDescription>
<Blazonry>/GOTDB;component/Images/Blazonry/Arryn.jpg</Blazonry>
<Motto>As High as Honor</Motto>
<Lord>Robin Arryn</Lord>
<Seat>The Eyrie</Seat>
<Region>The Vale of Arryn</Region>
<Military>Unknown</Military>
<Members>
<Member>Lord Jon Arryn (deceased)</Member>
<Member>Lady Lysa</Member>
<Member>Robin Arryn</Member>
<Member>Lady Alys</Member>
</Members>
<Tree>/GOTDB;component/Images/Trees/TreeArryn.jpg</Tree>
</House>

[...]
</Houses>

On WP7

Now that you have your XML, add it to your project as resource. Aaaaand, now the code !

XDocument doc = XDocument.Load("/GOTDB;component/Houses.xml");

var feeds2 = from feed in doc.Descendants("House")
select new HouseItem
{
Id = Convert.ToInt32(feed.Element("Id").Value),
Name = feed.Element("Name").Value,
[...]
Members = feed.Element("Members").Elements("Member").Select(x => x.Value.ToString()).ToList<String>()

};
maListe = feeds2.ToList();
listHouses.ItemsSource = maListe;

I create a new XDocument and load inside my XML (Don’t forget to change the path for your project). Foreach « House » I create a new HouseItem and extract the data for each member. Then I gather all the HouseItem in a list named maListe and assign it to a ListBox.

 

As you can see, it’s very easy to make. You have your data with a clear vision and you can use them simply in your app.