0

parse the xml file:

XmlTextReader reader = new XmlTextReader(fileName);
while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element: // The node is an element.
            Console.Write("<" + reader.Name);
            Console.WriteLine(">");
            break;
        case XmlNodeType.Text: //Display the text in each element.
            Console.WriteLine(reader.Value);
            break;
        case XmlNodeType.EndElement: //Display the end of the element.
            Console.Write("</" + reader.Name);
            Console.WriteLine(">");
            break;
    }
}

How do i now enter nodes to get a tree view of the xml file i'm parsing? This is what i have thus far:

<TreeView Margin="177,61" Name="myTreeView" ItemsSource="{Binding XPath=XmlNodeType.Element}" >
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding XPath=XmlNodeType.Element}">
            <TextBlock Text="{Binding XPath=XmlNodeType.Text}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

but nothing shows up.... just don't understand how to add nodes i guess...

1 Answer 1

2

You have to add the nodes in code behind like that:

var newNode = new TreeViewItem
{
    Header = "New Node"
};
myTreeView.Items.Add(newNode);

This adds a node to the top of the tree. If you want to build a hierarchy you have to add the node at the appropiate position like that:

// Find the node you want to have as parent.
var parentNode = myTreeView.Items.Cast<TreeViewItem>().FirstOrDefault(item => item.Header = "Parent Node");
if (parentNode != null)
{
    var newNode = new TreeViewItem
    {
        Header = "New Node"
    };
    parentNode.Items.Add(newNode);
}

BTW: I would use to x:Name Property to name the elements in Xaml, sometimes there is some trouble in code behind when you use only Name

3
  • Wow, this is so cool! Thanks for the help. Voted you up and selected your answer
    – BigBug
    Nov 21, 2011 at 8:16
  • hmmm seems to be a problem with this portion when creating a hierarchy "item.Header = "Parent Node")" Also, i don't think i quite understand that line. Would you be able to explain it to me?
    – BigBug
    Nov 21, 2011 at 8:35
  • That was only a sample to find a parent node. When you "walk" through your xml file and you've added a node, then you already have that parent node for all child nodes. The line I posted, do the following (as a sample!): It takes the all Items, cast them to TreeViewItem and searches the first node, that "Parent Node" set as header. Nov 21, 2011 at 8:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.