XML To Tree View

Tamilmaran
Posted by Tamilmaran under C# category on | Views : 2389
Xml To Treeview is a Windows application developed using C# and .Net. It is a very good project to learn C# basics and coding standards. The code is very well organised and properly commented.



Comments, Issues or Bugs in Application:

Please post your valuable comment here so that I will work on your comments to fine tune my next projects.

If you find any difficulty in using or understanding the application, please post your issues here.

If you find any bugs, please report here. I will rectify them. Also, you try to fix any bug you find so that you can understand the application better.

Please feel free to contact me at jagadesh97@gmail.com anytime.



private void button1_Click(object sender, EventArgs e)
{
treeView1.Nodes.Clear();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select XML file only";
ofd.CheckFileExists = false;
ofd.CheckPathExists = true;
ofd.AddExtension = true;
ofd.DefaultExt = "txt";
ofd.ShowReadOnly = true;
ofd.ShowHelp = true;
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
strfile = ofd.FileName.ToString();
if (!strfile.EndsWith("xml"))
{
MessageBox.Show("Plz Select XML File Only");
return;
}
DeserializeTreeView(treeView1, strfile);
groupBox2.Text = strfile;

}
public void DeserializeTreeView(TreeView treeView, string fileName)
{

XmlTextReader reader = null;
try
{
// disabling re-drawing of treeview till all nodes are added
treeView.BeginUpdate();

reader =
new XmlTextReader(fileName);

TreeNode parentNode = null;

while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{


TreeNode newNode = new TreeNode();
bool isEmptyElement = reader.IsEmptyElement;

newNode.Text = reader.Name;

// add new node to Parent Node or TreeView
if (parentNode != null)
parentNode.Nodes.Add(newNode);
else
treeView.Nodes.Add(newNode);

// making current node 'ParentNode' if its not empty
if (!isEmptyElement)
{
parentNode = newNode;
}
}
// moving up to in TreeView if end tag is encountered
else if (reader.NodeType == XmlNodeType.EndElement)
{


parentNode = parentNode.Parent;

}
else if (reader.NodeType == XmlNodeType.XmlDeclaration)
{ //Ignore Xml Declaration
}
else if (reader.NodeType == XmlNodeType.None)
{
return;
}
else if (reader.NodeType == XmlNodeType.Text)
{
parentNode.Nodes.Add(reader.Value);

}

}
}
finally
{

treeView.EndUpdate();
reader.Close();
}


Comments or Responses

Login to post response