Children of XElement

53,793

Solution 1

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

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

XElement.Nodes

Share:
53,793
Superman
Author by

Superman

Updated on December 28, 2020

Comments

  • Superman
    Superman over 3 years

    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.

  • rtpHarry
    rtpHarry almost 13 years
    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.
  • Bevan
    Bevan almost 13 years
    If you just want the first child, reguardless of name, try using Elements().FirstOrDefault().
  • Tacroy
    Tacroy almost 12 years
    Why couldn't they have just called it "XElement.Children"? Way more discoverable.
  • Bevan
    Bevan almost 12 years
    @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.
  • Zev Spitz
    Zev Spitz over 11 years
    @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.