2

Using Visual C# in Visual Studio 2010 I followed the following example to add the nodes of an XML document to a tree view.

http://support.microsoft.com/kb/317597/en-us

So far this works fine. However the given piece of code in #7 displays all nodes including the values, e.g. when reaching <myNode>2</myNode> the value 2 is also displayed.

How can I change the example so that only all node names excluding their value will be populated to the tree view?

1 Answer 1

2

Notice the piece of code that goes:

if (inXmlNode.HasChildNodes)
{
    // child nodes
    for (...)
    {
        xNode = inXmlNode.ChildNodes[i];
        inTreeNode.Nodes.Add(new TreeNode(xNode.Name));  // here the leafs are created
        tNode = inTreeNode.Nodes[i];
        AddNode(xNode, tNode);
    }
}
else
{
    // it's a leaf
    inTreeNode.Text = ...  // here it is set
}

For your requirement you ought to restructure the whole recursive method but a simple fix is to move the HasChildNodes up:

if (inXmlNode.HasChildNodes)
{
    // child nodes
    for (...)
    {
        xNode = inXmlNode.ChildNodes[i];

        if (! xNode.HasChildNodes) // a leaf?
           continue;  // then skip 

        inTreeNode.Nodes.Add(new TreeNode(xNode.Name));  // here the leafs are created
        tNode = inTreeNode.Nodes[i];
        AddNode(xNode, tNode);
    }
}
else
{
    // it's a leaf, should only happen for the root now
    inTreeNode.Text = ...  // here it is set
}     
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works fine! I just stick with your solution without restructuring the method :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.