views:

33

answers:

1

In a treeview you can retrieve the level of an item. I am trying to accomplish the same thing with the given input being an object.

The XML data I will use for this example would be something like the following

<?xml version="1.0" encoding="utf-8" ?>
<Testing>
  <Numbers>
    <Number val="1">
      <Number val="1.1">
        <Number val="1.1.1">
          <Number val="1.1.2" />
          <Number val="1.1.3" />
          <Number val="1.1.4" />
        </Number>   
      </Number>
      <Number val="1.2" />
      <Number val="1.3" />
      <Number val="1.4" />
    </Number>
    <Number val="2" />
    <Number val="3" />
    <Number val="4" />
  </Numbers>
  <Numbers>
    <Number val="5" />
    <Number val="6" />
    <Number val="7" />
    <Number val="8" />
  </Numbers>
</Testing>

This one is kicking my butt!

+1  A: 

You can recurse the element's parents, like this:

public static void GetLevel(this XObject node) {
    if (node.Parent == null) return 0;
    return 1 + node.Parent.GetLevel();
}

Or, without recursion:

public static void GetLevel(this XObject node) {
    int level = 0;
    while (null != (node = node.Parent))
        level++;

    return level;
}
SLaks
I just noticed that my input object is actually a ObservableCollection<Number> and this makes syntax like .Parent unavailable.
Ryan
Then which node do you want the parent for?
SLaks
Ryan
Then this isn't LINQ-to-XML. This is not possible, since your `Number` class doesn't track its parent `Number`.
SLaks
I was thinking I needed to add a level value. Thanks for taking a look.
Ryan