Looping through xml building a TreeView using C#

This code is for iterating the xml all the way down, this is for a 4 level deep structure but can easily be adjusted, to insert it into a TreeView, in .Net.


Xml:
<?xml version="1.0" encoding="utf-8" ?>
<data>
  <process name="Process_1">
    <processPart name="Part11" />
    <processPart name="part12">
      <workflow name="WorkFlowz111" />
    </processPart>
  </process>
  <process name="Process_2">
      <processPart name="Part21" />
      <processPart name="part22">        
        <workflow name="WorkFlowz221" />
      </processPart>    
  </process>
</data>

Methods:

 public TreeView GetTreeViewFromXML(TreeView tree)  
 {  
   TreeNode node1 = new TreeNode("Processer","");  
   node1.Expanded = false;  
   XmlDocument xDoc = new XmlDocument();  
   xDoc.LoadXml(ep.GetProcessStructureXML());  
   tree.Nodes.Add(GetTreeNodeFromSiblings(xDoc.ChildNodes[1], node1, selectedvalue));  
   return tree;  
 }  
 private TreeNode GetTreeNodeFromSiblings(XmlNode next, TreeNode node)  
 {  
   foreach (XmlNode nod in next.ChildNodes)  
   {  
     TreeNode tn = new TreeNode(nod.Attributes["name"].Value,  
       nod.Attributes["name"].Value);  
     if (nod.HasChildNodes)  
       node.ChildNodes.Add(GetTreeNodeFromSiblings(nod.CloneNode(true), tn));  
     else  
       node.ChildNodes.Add(tn);  
   }  
   return node;  
 }  

And for the aspx codebehind C#, need to select current value and expand the tree down that path.

 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     Tree1 = em.GetTreeViewFromXML(Tree1);  
     if (Request["selectedvalue"] != null)  
     {  
       selectedvaluepath = Request["selectedvalue"].ToString();  
       sel_value.Value = selectedvaluepath;  
       TreeNode noded = Tree1.FindNode(selectedvaluepath);  
       if (noded != null)  
       {  
         noded.Select();  
         noded.Expanded = false;  
         TreeNode parent = ExpandParent(noded);  
         TreeNode parent2 = ExpandParent(parent);  
         TreeNode parent3 = ExpandParent(parent2);  
         btnSendBack.Disabled = false;  
       }  
     }  
   }  
 }  
 protected void tree_selected(object sender, EventArgs e)  
 {  
   btnSendBack.Disabled = true;  
   string t = Tree1.SelectedNode.ValuePath;  
   if (!string.IsNullOrEmpty(t))  
   {  
     sel_value.Value = t;  
     btnSendBack.Disabled = false;  
   }  
 }  
 private TreeNode ExpandParent(TreeNode node)  
 {  
   if (node == null)  
     return null;  
   TreeNode parent = node.Parent;  
   if (parent != null)  
   {  
     parent.Expanded = true;  
     return parent;  
   }  
   return null;  
 }  

1 kommentar: