Navigating/Querying an X-DOM

As you might expect, the XNode and XContainer classes define methods and properties for traversing the X-DOM tree. Unlike a conventional DOM, however, these functions don’t return a collection that implements IList<T>. Instead, they return either a single value or a sequence that implements IEnumerable<T> —upon which you are then expected to execute a LINQ query (or enumerate with a foreach ). This allows for advanced queries as well as simple navigation tasks—using familiar LINQ query syntax.

Note

Element and attribute names are case-sensitive in the XDOM—just as they are in XML.

Child Node Navigation

Return type

Members

Works on

XNode

FirstNode

XContainer

 

LastNode

XContainer

IEnumerable

Nodes()

XContainer*

<XNode>

DescendantNodes()

XContainer*

 

DescendantNodesAndSelf()

XElement*

XElement

Element (XName)

XContainer

IEnumerable

Elements()

XContainer*

<XElement>

Elements(XName)

XContainer*

 

Descendants()

XContainer*

 

Descendants(XName)

XContainer*

 

DescendantsAndSelf()

XElement*

 

DescendantsAndSelf(XName)

XElement*

bool

HasElements

XElement

Note

Functions marked with an asterisk in the third column of this table (and others following) also operate on sequences of the same type. For instance, you can call Nodes on either an XContainer or a sequence of XContainer objects. This is possible because of extension methods defined in System.Xml.Linq—the supplementary query operators we talked about in the overview.

FirstNode, LastNode, ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.