69

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.

Superman
  • 3,686
  • 6
  • 34
  • 46

3 Answers3

112

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.

Bevan
  • 43,618
  • 10
  • 81
  • 133
  • This seems to have solved the OPs question but there is no parameterless overload for `Element()` so this doesn't help me to get the first child when I know that its `XName` can vary. – rtpHarry Jul 25 '11 at 12:30
  • 3
    If you just want the first child, reguardless of name, try using `Elements().FirstOrDefault()`. – Bevan Jul 25 '11 at 22:32
  • 3
    Why couldn't they have just called it "XElement.Children"? Way more discoverable. – Tacroy May 10 '12 at 16:21
  • 7
    @Tacroy Each XElement has two sets of children, either of which may be empty. One is the ordered set of child *elements*, the other is a set of child *attributes* - whichever one you think should be found in *Children*, others would disagree. Using `Elements` and `Attributes` follows the nomenclature of the Xml standard. – Bevan May 12 '12 at 02:15
  • 2
    @Bevan I think the better answer would be that there may also be a set of **nodes**, each of which might not be an element. Attributes are not actually children of the element. – Zev Spitz Dec 27 '12 at 20:07
13

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>()
Steven Robbins
  • 26,441
  • 7
  • 76
  • 90
4

XElement.Nodes

tvanfosson
  • 524,688
  • 99
  • 697
  • 795