Here's a basic example of how to implement XML to TreeView binding. XmlDataProvider allows you to load an XML document and bind to it. HierarchicalDataTemplate allows you to define TreeView templates with sub-items. XPath must be used to bind instead of Path, and the @ symbol prefix indicates binding to an attribute.
<Window x:Class="Testing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<XmlDataProvider x:Key="people" XPath="People" />
<HierarchicalDataTemplate x:Key="colorsTemplate">
<TextBox Text="{Binding XPath=@Name, Mode=TwoWay}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="rootTemplate" ItemsSource="{Binding XPath=FavoriteColors/Color}" ItemTemplate="{StaticResource colorsTemplate}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding XPath=@FirstName, Mode=TwoWay}" />
<TextBlock Text=" " />
<TextBox Text="{Binding XPath=@LastName, Mode=TwoWay}" />
<TextBlock Text=" (Age: " />
<TextBox Text="{Binding XPath=@Age, Mode=TwoWay}" />
<TextBlock Text=")" />
</StackPanel>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Source={StaticResource people}, XPath=Person}" ItemTemplate="{StaticResource rootTemplate}" Grid.ColumnSpan="2" />
</Grid>
</Window>
Using the following XML file:
<?xml version="1.0" encoding="utf-8" ?>
<People>
<Person FirstName="Ringo" LastName="Starr" Age="72">
<FavoriteColors />
</Person>
<Person FirstName="George" LastName="Harrison" Age="52">
<FavoriteColors>
<Color Name="Orange" />
<Color Name="Green" />
<Color Name="Purple" />
</FavoriteColors>
</Person>
<Person FirstName="Paul" LastName="McCartney" Age="42">
<FavoriteColors>
<Color Name="White" />
</FavoriteColors>
</Person>
<Person FirstName="John" LastName="Lennon" Age="33">
<FavoriteColors>
<Color Name="Red" />
<Color Name="Green" />
</FavoriteColors>
</Person>
</People>
And the following code-behind:
XmlDataProvider people;
public MainWindow()
{
InitializeComponent();
people = FindResource("people") as XmlDataProvider;
var xmlDocument = new XmlDocument();
xmlDocument.Load("People.xml");
people.Document = xmlDocument;
}
As you can see I am loading the XML document in code, so you can load it into an XDocument or XmlDocument class and sort it how you want. Then you should be able to save it back to file at some point.
EDIT:
Here's an example of loading and saving at runtime:
private void Load_Click(object sender, RoutedEventArgs e)
{
var xmlDocument = new XmlDocument();
xmlDocument.Load("People.xml");
people.Document = xmlDocument;
}
private void Save_Click(object sender, RoutedEventArgs e)
{
XmlDocument xml = people.Document;
if (xml != null)
{
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
if ((bool)sfd.ShowDialog(this))
{
xml.Save(sfd.FileName);
}
}
}