Damian Helaey

Damian Helaey

  • NA
  • 7
  • 4.4k

Need a recursive method to create a treeview for a WPF app

Dec 18 2013 6:19 PM

I am having difficulty recreating a tree view from an  XML file in a WPF application

I require the tree structure to be displayed with check boxes
Here is a typical XML file I will be reading

<A>
<B>

       <BTest1>

       </BTest1>

       <BTest2>

       </BTest2>

   <C>

      <D>

          <DTest1>

          </DTest1>

          <DTest2>

          </DTest2>

      </D>

   </C>

</B>

<E>

       <F>

          <FTest1>

          </FTest1>

          <FTest2>

          </FTest2>

     </F>

</E>

Here is the MainWindow Class that uses a Node class for the check boxes

namespace WpfApplication

{

    public partial class MainWindow : Window

    {

        public ObservableCollection<Node> Nodes { get; private set; }

        public MainWindow()

        {

            Nodes = new ObservableCollection<Node>();

            Nodes.Clear();

            InitializeComponent();

            XmlDocument doc = new XmlDocument();

            doc.Load(@"C:\Temp\simple.xml");

            XmlNode root = doc.DocumentElement;

            TreeViewItem testItems = new TreeViewItem();

            //Read in the XML and create parent child nodes

            xmlToParentChildNodes(root);

            treeView.ItemsSource = Nodes;

        }

        private void xmlToParentChildNodes(XmlNode node)

        {

            var parent = new Node() { Text = node.Name.ToString() };

            var children = node.ChildNodes.Count;

            int currentNodeCount = Nodes.Count;

            if (node.ChildNodes.Count > 0)

            // Dont add children to the view if they dont have a parent

            {

                Nodes.Add(parent);

            }

            foreach (XmlNode child in node.ChildNodes)

            {

                var childNode = new Node() { Text = child.Name.ToString() };

                //*********************** Debug *********************

                System.Diagnostics.Debug.WriteLine("Node Reference=" + currentNodeCount +" Parent=" + node.Name.ToString() + " No of Children=" + children + " childNode=" + child.Name.ToString());

                //*********************** Debug ********************

                parent.Children.Add(childNode);

                xmlToParentChildNodes(child);

            }

        }

The following structure is produced

NodeParentChildren
0AB,E
1BBTest1,BTest2,C
2CD
3DDTest1,DTest2
4EF
5FFTest1, FTest2

 

A recursive method is probably required to recreate the hierarchy - I am a novice programmer and have been strugglling with this for a long time.

Could somebody please help?


Answers (6)