tags:

views:

365

answers:

1

I'm using C# and LINQ to traverse my XDocument.

Lets say I have XML like this:

<Root>
  <Element ID="1">
    <Element ID="2">
      <Element ID="3" />
      ...
    </Element>
    <Element ID="50">
      ...
    </Element>
  </Element>
  <Element ID="x">
    ...
  </Element>
</Root>

Now let's say I have the ID 3, and manage to find the element with that ID. At this point, I want to find the ID of the top-level parent node (it's parent which is one level below the Root). In this instance, I want to find the Element with ID 1. I can do this:

myElement.Parent.Parent

But I don't know how many levels up it might be - so I probably need recursion. However, I recall XDocument's being read forward-only. How expensive is it to find the Parent - recursively? What is the best way to do this?

My XML files could be upto 500k big.

+1  A: 

No, XDocument isn't forward-only. Are you thinking of XStreamingElement?

I believe the parent is stored as a field as part of XObject, so fetching it recursively is cheap.

Jon Skeet
I have a LINQ book here and it says that XNode internally uses a singly linked list, so calling PreviousNode is nonperformant. I was worried that Parent might also be similarly nonperformant.
Alex York
Right - no, I don't believe that's the case. Try it on the biggest document you're likely to see, and time it :)
Jon Skeet