Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the first child of an XElement?

Tags:

c#

.net

vb.net

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

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

like image 340
Thalecress Avatar asked Aug 13 '13 21:08

Thalecress


2 Answers

You want 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 output:

<B y="data">
    <C/>
</B>
like image 146
Timothy Shields Avatar answered Oct 26 '22 06:10

Timothy Shields


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

like image 40
Adrian Wragg Avatar answered Oct 26 '22 06:10

Adrian Wragg