O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required