How to get the first child of an XElement?

The old XmlElement class had a FirstChild property. What is the equivalent of XElement?

Visual Studio rejects .Element () ,. Elements () [0].

EDIT: Thanks for all the suggestions. I did not understand that I needed to import System.Linq to use the First method.

Using System.Linq .Elements.First 

or

 Using System.Linq Descendants.First 

or

 .FirstNode 
+7
source share
2 answers

You need the IEnumerable<XElement> Descendants() method of the XElement class.

 XElement element = ...; XElement firstChild = element.Descendants().First(); 

This sample program:

 var document = XDocument.Parse(@" <A x=""some""> <B y=""data""> <C/> </B> <D/> </A> "); Console.WriteLine(document.Root.Descendants().First().ToString()); 

Produces this conclusion:

 <B y="data"> <C/> </B> 
+8
source share

http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx claims that XElement has a FirstNode property inherited from XContainer . This is described as the first child of the current node, and probably this is what you need.

+4
source share

All Articles