Find Elements with an XPath Search

Problem

You need to search an XML document or a portion of an XML document for nodes that match certain criteria.

Solution

Use an XPath expression with the SelectNodes or SelectSingleNode method.

Discussion

The XmlNode class defines two methods that perform XPath searches: SelectNodes and SelectSingleNode. These methods operate on all contained child nodes. Because the XmlDocument inherits from XmlNode, you can call XmlDocument.SelectNodes to search an entire document.

Basic XPath syntax uses a pathlike notation. For example, the path /Order/Items/Item indicates an Item element that is nested inside an Items element, which, in turn, in nested in a root Order element. This is an absolute path. The following example ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook 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.