Source: queryNodes.frm
This example application calls both the selectSingleNode
method and the selectNodes
method on an XML DOM object loaded from the stocks.xml file. The same XPath expression is input to both methods:
//stock[1]/*
This expression specifies all the child elements of the first <stock>
element in the XML document. In MSXML, the selectSingleNode
method returns the first element of the resultant node-set, and the selectNodes
method returns all the elements in the node-set.
Programmatically, this source code performs the following steps:
Creates an instance of an XML DOM object (
oXMLDom
).Calls the
load
method onoXMLDom
to load XML data from a file (stocks.xml).Calls the
selectSingleNode
method onoXMLDom
to select a DOM node according to the input XPath expression (//stock[1]/*
). Then displays the resulting node in the console if the query is successful.Calls the
selectNodes
method onoXMLDom
to select a DOM node-set according to the input XPath expression ("//stock[1]/*
"). Then displays the resulting nodes in the console if the query is successful.
Visual Basic Source File (queryNodes.frm)
Private Sub Form_Load()
' Output string:
Dim strout As String
strout = ""
' Load an xml document into a DOM instance.
Dim oXMLDom As New DOMDocument60
oXMLDom.async = False
oXMLDom.validateOnParse = False
oXMLDom.resolveExternals = False
oXMLDom.preserveWhiteSpace = True
If oXMLDom.Load(App.Path + "\stocks.xml") = False Then
MsgBox "Failed to load xml data from file."
Exit Sub
End If
' Query a single node.
Dim oNode As IXMLDOMNode
Set oNode = oXMLDom.selectSingleNode("//stock[1]/*")
If oNode Is Nothing Then GoTo MoreNodes
strout = strout _
+ "Result from selectSingleNode" + vbNewLine _
+ "Node, <" + oNode.nodeName + ">: " + vbNewLine _
+ vbTab + oNode.xml + vbNewLine + vbNewLine
MoreNodes:
' Query a node-set.
Dim oNodes As IXMLDOMNodeList
Set oNodes = oXMLDom.selectNodes("//stock[1]/*")
strout = strout _
+ "Results from selectNodes:" + vbNewLine
For i = 0 To oNodes.length - 1
Set oNode = oNodes.nextNode
If Not (oNode Is Nothing) Then
sName = oNode.nodeName
sData = oNode.xml
strout = strout _
+ "Node (" + CStr(i) + "), <" + sName + ">:" _
+ vbNewLine + vbTab + sData + vbNewLine
End If
Next
MsgBox strout
End Sub
To add queryNodes.frm to the project
- Copy the code listing above. Paste it into the Visual Basic code editor as the form_load subroutine, replacing any code fragments that are already there.
Next, we'll add the resource files to the queryNodes project.