I'm creating a XML-viewer which should be able to read every XML file and put it in a treeview.
My goal is to create a XMLViewer control, an user should be able to change certain routines in his own implementations. I provide default implementations that offer a basic functionality so that the XML viewer at least shows a default behaviour.
What I have so far:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML Files|*.xml";
ofd.InitialDirectory = @"C:\";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName.ToString();
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ofd.FileName);
treeView1.Nodes.Clear();
treeView1.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = (TreeNode)treeView1.Nodes[0];
addTreeNode(xDoc.DocumentElement, tNode);
treeView1.ExpandAll();
}
}
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
if (xmlNode.HasChildNodes) //The current node has children
{
xNodeList = xmlNode.ChildNodes;
for (int x = 0; x <= xNodeList.Count - 1; x++)
{
xNode = xmlNode.ChildNodes[x];
treeNode.Nodes.Add(new TreeNode(xNode.Name));
treeNode.ForeColor = Color.Red;
tNode = treeNode.Nodes[x];
tNode.ForeColor = Color.Green;
addTreeNode(xNode, tNode);
}
}
else
treeNode.Text = xmlNode.OuterXml.Trim();
}
Results in:
What I want:
Any ideas? :)
Thanks in advance!