Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Intermediate
Oct 19, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
Dino Esposito
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date