Children of XElement

C#XmlLinq to-XmlXelement

C# Problem Overview


How do I get just the children of an XElement?

I am currently using the XElement.Descendants() function, which returns all levels of XElements, rather than just the child nodes.

What I would really like is an IEnumerable of just the children.

C# Solutions


Solution 1 - C#

The immediate child elements of one XElement are accessible by calling the Element() or Elements() functions. Use the overloads with a name to access specific elements, or without to access all child elements.

There are also similar methods like Attribute() and Attributes() that you might find useful.

Solution 2 - C#

XElement.Nodes() should get you what you want.

If you just want the XElement child nodes then you might need to restrict it (depending on your XML) with:

XElement.Nodes().OfType<XElement>()

Solution 3 - C#

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSupermanView Question on Stackoverflow
Solution 1 - C#BevanView Answer on Stackoverflow
Solution 2 - C#Steven RobbinsView Answer on Stackoverflow
Solution 3 - C#tvanfossonView Answer on Stackoverflow