populate a tree view with an xml file
- by syedsaleemss
Im using .net windows form application. I have an xml file.I want to populate a tree view with data from a xml file. I am doing this using the following code.
private void button1_Click(object sender, EventArgs e)
{
try
{
this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
//string strXPath = "languages";
string strRootNode = "Treeview Sample";
OpenFileDialog Dlg = new OpenFileDialog();
Dlg.Filter = "All files(*.*)|*.*|xml file (*.xml)|*.txt";
Dlg.CheckFileExists = true;
string xmlfilename = "";
if (Dlg.ShowDialog() == DialogResult.OK)
{
xmlfilename = Dlg.FileName;
}
// Load the XML file.
//XmlDocument dom = new XmlDocument();
//dom.Load(xmlfilename);
XmlDocument doc = new XmlDocument();
doc.Load(xmlfilename);
string rootName = doc.SelectSingleNode("/*").Name;
textBox4.Text = rootName.ToString();
//XmlNode root = dom.LastChild;
//textBox4.Text = root.Name.ToString();
// Load the XML into the TreeView.
this.treeView1.Nodes.Clear();
this.treeView1.Nodes.Add(new TreeNode(strRootNode));
TreeNode tNode = new TreeNode();
tNode = this.treeView1.Nodes[0];
XmlNodeList oNodes = doc.SelectNodes(textBox4.Text);
XmlNode xNode = oNodes.Item(0).ParentNode;
AddNode(ref xNode, ref tNode);
this.treeView1.CollapseAll();
this.treeView1.Nodes[0].Expand();
this.Cursor = System.Windows.Forms.Cursors.Default;
}
catch (Exception ex)
{
this.Cursor = System.Windows.Forms.Cursors.Default;
MessageBox.Show(ex.Message, "Error");
}
}
private void AddNode(ref XmlNode inXmlNode, ref TreeNode inTreeNode)
{
// Recursive routine to walk the XML DOM and add its nodes to a TreeView.
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;
// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(ref xNode, ref tNode);
}
}
else
{
inTreeNode.Text = inXmlNode.OuterXml.Trim();
}
}
My xml file is this:"hello.xml"
-
-
abc
hello how ru
-
def
i m fine
-
ghi
how abt u
Now after using the above code I am able to populate the tree view. But I dont like to populate the complete xml file. I should get only till
languages
language
key
value
I don't want abc
how are you etc..... I mean to say the leaf nodes. Please help me