devxlogo

A better way to query for a single node

A better way to query for a single node

In the XmlNode class, that is the class that provides node functionality in an XMLDOM representation of an XML document, the SelectNodes (and the ancillary SelectSingleNode) method exploits the XPath query language to let you extract nodes based on logical conditions. The SelectNodes methods return a collection of XmlNode object, whereas SelectSingleNode returns only the first node that match the XPath criteria. However, a quick look at the implementation of SelectSingleNode suggests that using SelectNodes is often preferable. The following pseudocode shows the internal working of SelectSingleNode:

Public Function SelectSingleNode(xpathExpr As String) As XmlNode   Dim nodes As XmlNodeList = SelectNodes(xpath)   Return nodes(0)End Funtion

The SelectSingleNode method internally calls SelectNodes and retrieves all the nodes that match a given XPath expression. Next it simply returns the first selected node to the caller. Using SelectSingleNode perhaps results in a more easily readable code, but doing so certainly does not improve the performance of the application when you need just one node. A better way to query for a single node is using a smarter XPath expression. The idea is that you place a stronger filter on the XPath expression so that it returns just the node, or the nodes, you want. For example, to get only the first node, use the following query:

doc.SelectSingleNode("NorthwindEmployees/Employee[position() = 1]")

The use of SelectSingleNode in this case simply serves the purpose of returning a XmlNode object rather than an array of objects.


Source: Applied XML Programming for Microsoft .NET, Dino Esposito, Microsoft Press 2002

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist