Keith:
I did something like this a while ago as a test of sorts. This should get you started (just ignore the filehandler stuff, that was C++ code)
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
// Create an OpenFileDialogBox to select the text file to read.
this.ofdFilePicker.InitialDirectory = Environment.CurrentDirectory;
this.ofdFilePicker.Filter = "text files (*.txt)|*.txt";
if (this.ofdFilePicker.ShowDialog() == DialogResult.OK)
{
try
{
// Create a new XML document.
XmlDocument doc = new XmlDocument();
// Read the contents of a file using the C++ file reader
// and load it into the XMLDoc.
string xmlDoc = fileHandler.readFile(this.ofdFilePicker.FileName);
doc.LoadXml(xmlDoc);
// Clear the treeview nodes and then start adding nodes too
// it from the file.
this.tvXMLViewer.Nodes.Clear();
TreeNode rootNode = this.tvXMLViewer.Nodes.Add(doc.DocumentElement.Name);
// Call our TreeClimber function to traverse the XML nodes and
// populate the TreeView
this.xmlTreeClimber(doc.DocumentElement, rootNode);
this.tvXMLViewer.ExpandAll();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not generate a treeview from the specified XML document. Original error: " + ex.Message);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read XML file. Original error: " + ex.Message);
}
}
private void xmlTreeClimber(System.Xml.XmlNode node, TreeNode treeNode)
{
// Process the child nodes if available.
if (node.HasChildNodes)
{
// Loop through all the child nodes.
XmlNodeList nodeList = node.ChildNodes;
for (int count = 0; count <= nodeList.Count - 1; count++)
{
XmlNode newXNode = node.ChildNodes[count];
treeNode.Nodes.Add(new TreeNode(newXNode.Name));
TreeNode newTNode = treeNode.Nodes[count];
// recursively call xmlTreeClimber.
xmlTreeClimber(newXNode, newTNode);
}
}
else
{
// If no children use trimmed OuterXML.
treeNode.Text = node.OuterXml.Trim();
}
}
private void XmlTreeBuilder(TreeNodeCollection tnCollection)
{
// Loop through all nodes in the collection.
foreach (TreeNode node in tnCollection)
{
// If the node has children recursivley call XmlTreeBuilder.
if (node.Nodes.Count > 0)
{
xmlWriter.WriteStartElement(node.Text);
XmlTreeBuilder(node.Nodes);
xmlWriter.WriteEndElement();
}
else
{
// If no children just write the text.
xmlWriter.WriteString(node.Text);
}
}
}