This is XML file
<Root>
<RootNode name="CurrentDbName" value="DeltaTest Backup" DesiPath="E:\BuildBackups">
<ChildNode name="Application" value="App">
<LeafNode name="Source" value="Source" SourcePath="E:\Alertv2" />
<LeafNode name="Publish" value="Publish" SourcePath="C:\Alert_Source" />
</ChildNode>
<ChildNode name="Database" value="DB">
<LeafNode name="Dev" value="Dev" SourcePath="C:\Kiran3" />
<LeafNode name="Build" value="Build" SourcePath="C:\Kiran4" />
</ChildNode>
</RootNode> </Root>
From this, I want to create a treeview in WPF and looks like
-Root
--DeltaTestBaclup
---App
----Source
----Publish
---Db
----Dev
----Build
So please help me to create this treeview.
Create an object of the class TreeviewItem in the class label and in the windows Load event handler create an XmlReaderSettings object and set its IgnoreWhitespace property to true so that the insignificant whitespace in the XML document is ignored.
A TreeView represents data in a hierarchical view in a parent child relationship where a parent node can be expanded or collapsed. The left side bar of Windows Explorer is an example of a TreeView.
The tree structure is often referred to as XML Tree and plays an important role to describe any XML document easily. The tree structure contains root (parent) elements, child elements and so on. By using tree structure, you can get to know all succeeding branches and sub-branches starting from the root.
Here is a way to do it programmatically. This is based on this website's solution
public YourWindow()
{
InitializeComponent();
BuildTree(treeView, XDocument.Load(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"testxml.xml")));
}
private void BuildTree(TreeView treeView, XDocument doc)
{
TreeViewItem treeNode = new TreeViewItem
{
//Should be Root
Header = doc.Root.Name.LocalName,
IsExpanded = true
};
treeView.Items.Add(treeNode);
BuildNodes(treeNode, doc.Root);
}
private void BuildNodes(TreeViewItem treeNode, XElement element)
{
foreach (XNode child in element.Nodes())
{
switch (child.NodeType)
{
case XmlNodeType.Element:
XElement childElement = child as XElement;
TreeViewItem childTreeNode = new TreeViewItem
{
//Get First attribute where it is equal to value
Header = childElement.Attributes().First(s => s.Name == "value").Value ,
//Automatically expand elements
IsExpanded = true
};
treeNode.Items.Add(childTreeNode);
BuildNodes(childTreeNode, childElement);
break;
case XmlNodeType.Text:
XText childText = child as XText;
treeNode.Items.Add(new TreeViewItem { Header = childText.Value, });
break;
}
}
}
That code behind will build the tree to your spec. This is the XAML
<Grid>
<TreeView Margin="20" Background="LightGray" x:Name="treeView" />
</Grid>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With