Databind xml to a treeview
-
Aha the urgent guy! So now you are back with a different title line. First of all, do you want only the DATA part of the XML in your tree view? If you go the normal examples shown in MSDN etc, you will get BOTH TAGNAMES AND DATA in your treeview. As you ar repeatedly asking the question, I am assuming that you need ONLY THE DATA (b'coz otherwise you would have altready got your answer from MSDN etc). Here is the basic idea of how you can do it. The whole code will be too complex to fit in here. First aof all see the MSDN example from (probably your post only): http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=450892&SiteID=1[^]. From that MSDN example, I will modify ONLY THE button1_Click() method. Not the AddNode() method. You have to follow a slightly different approach here:
private void button1_Click(object sender, EventArgs e)
{
try
{
// SECTION 1. Create a DOM Document and load the XML data into it.
XmlDocument dom = new XmlDocument();
dom.Load(Application.StartupPath + "\\Sample.xml");// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();// SECTION 3. Populate the TreeView with the DOM nodes.
if( dom.DocumentElement.Text == null || dom.DocumentElement.Text == "" )
treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
else
treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Text));if (dom.DocumentElement.HasChildNodes)
{
XmlNodeList nodeList = dom.DocumentElement.ChildNodes;
for(i = 0; i<=nodeList.Count - 1; i++)
{
if( ! ( ( nodeList[i].ChildNodes.Count == 1 )
&& ( nodeList[i].InnerXml == nodeList[i].InnerText ) ) )
AddNode(nodeList[i], treeView1.Nodes[0]);
}
}treeView1.ExpandAll();
}
catch (XmlException xmlEx) { MessageBox.Show(xmlEx.Message); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}Note: Instead of calling AddNode once (as shown in MSDN example) I am calling it for all the childnodes in a loop. That eliminates 1 layer - your trr view won't have the level 2 tags. But now in the AddNode() method, what do you do? Answer is you have to follow a similar logic. Note the catch logic:
if( ! ( ( nodeList[i].ChildNodes.Count == 1 )
&& ( nodeList[i].InnerXml == nodeList[i].InnerText ) )