Working with XML data couldn't be easier in WPF. Just add an XMLDataProvider to your XAML and provide the location
of your XML resource. Once the provider is configured it can serve as a data-source to a WPF binding, it works similar to the way you bind to other data sources. For this article I will use a local XML file as the source. Here is what the sample XML looks like.
< ?xml version="1.0" encoding="utf-8" ?> <Foods> <Category CategoryName="Fruit"> <Food FoodName="Apple"> <Calories>140</Calories> <Price>1.49</Price> <PriceUnit>Pound</PriceUnit> </Food> <Food FoodName="Grapes"> <Calories>220</Calories> <Price>1.15</Price> <PriceUnit>Stem</PriceUnit> </Food> </Category> <Category CategoryName="Bakery"> <Food FoodName="Donut" > <Calories>450</Calories> <Price>.59</Price> <PriceUnit>Item</PriceUnit> </Food> </Category> </Foods>
Now that we have our source, it's simply a matter of creating the XMLDataProvider and setting the Source property to the XML file.
Once the XML data source in ready, you can use standard XAML binding to retrieve the data. Note that you can use XPath syntax to grab a subsection of the XML for your binding. In the following XAML there are two TextBlocks bound to the FoodsSource XMLDataProvider. The first TextBlock binds to the Category element, which contains several food items. The second TextBlock binds to the FoodName attribute.
As you can see in the following screenshot the TextBlocks show the bound data. The content in the first TextBlock looks wrong however. That's because the binding is to the Category element, which contains sub elements. The binding loads all the child data into one big string which is probably not the output you want.
Using hierarchical controlsFrequently, XML data is shown in a hierarchical fashion. To accommodate this type of layout there are certain elements in WPF (Menu, TreeView) that can display nested data. This next example shows how to use a Treeview to show the data. Before learning how to setup a TreeView, we need to discuss DataTemplates. As you may know, templates are a way to substitute an alternate UI for controls and data. Parent elements in the tree use the HierarchicalDataTemplate to provide the substitute UI for the element. When configured correctly the parent will show an expandable triangle in UI. Here is a simple HierarchicalDataTemplate that provides a TextBlock with the word 'Foods' when rendering the Food node in the Tree.
And here's what the template looks like in the TreeView.
That was easy. Now it's time to add two more HierarchicalDataTemplates to the application. Notice that the Calorie, Price and PriceUnit element are leaf nodes and have no children. Therefore they do not need a HierarchicalDataTemplate. If you want to template a leaf node, use a standard DataTemplate instead.