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
Author by
Superman
Updated on December 28, 2020Comments
-
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 almost 13 yearsThis 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 itsXName
can vary. -
Bevan almost 13 yearsIf you just want the first child, reguardless of name, try using
Elements().FirstOrDefault()
. -
Tacroy almost 12 yearsWhy couldn't they have just called it "XElement.Children"? Way more discoverable.
-
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
andAttributes
follows the nomenclature of the Xml standard. -
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.