views:

320

answers:

1

I currently have some XML similar to the following

<First Node>
    <Second Node>
        <Third Node>
            <Fourth Node>
               'Lots of Children in here
            </Fourth Node>
        </Third Node>
    </Second Node>
</First Node>

The issue is I know the exact names of the First, Second and Fourth Nodes. However the Third Node can be from a very wide range of possible names. I have no way to change the structure of the XML when it's being created(it's coming from a third party interface).

I've attempted some linq similar to the following

tempElement = (From secondElement In xmlDoc.Descendants Select XMLDoc.Element("First Node").Element("Second Node")).FirstOrDefault

I'm using that to trim down unnecessary XML. So after that I have a XElement with

<Second Node>
    <Third Node>
        <Fourth Node>
        </Fourth Node>
    </Third Node>
</Second Node>

Then on that I'm using this linq statement to try to return just the Fourth Node

fourthElement = tempElement.ElementsAfterSelf.FirstOrDefault

This is returning me a null value. What would be the correct linq there, or is there a better way to do this?

Thanks

+1  A: 

Just use Elements() instead of ElementsAfterSelf() - currently it's looking for elements after SecondNode instead of elements within SecondNode.

Jon Skeet
Thank you sir, that is so completely obvious now. Thinking about the ElementsAfterSelf in a grammatic form makes it make sense, what I wanted was an ElementsInSelf, which is what Elements provides.Also this is unrelated but do you know if the end of your SO DevDays talk video was ever uploaded?
msarchet
@msarchet: I don't think so, no. I can't remember whether my video camera battery died or whether there was some other reason.
Jon Skeet