Microsoft KB Archive/288913

= How To Use XPath Queries in MSXML DOM selectNodes Method =

Article ID: 288913

Article Last Modified on 7/15/2004

-

APPLIES TO


 * Microsoft XML Parser 2.6
 * Microsoft XML Core Services 4.0
 * Microsoft XML Core Services 4.0
 * Microsoft Visual Basic 6.0 Enterprise Edition

-



This article was previously published under Q288913



SUMMARY
XML Path Language (XPath) queries can be used to query the XML documents with DOM methods such as selectNodes or selectSingleNode. The default query that is used is XSLPattern for backward compatibility. To use XPath, change the SelectionLanguage internal property of DOMDocument to XPath. XPath adds lot of functionality; for example, it allows you to use functions such as string-length and sum.



MORE INFORMATION
The following code sample demonstrates how to use XPath with the selectNodes method:  Start Visual Basic and create a new Standard EXE. On the menu, select Projects, select References, and then add a reference to Microsoft XML, v3.0.  Add the following code to your Form_Load event: Dim dom As DOMDocument30 Dim nodelist As IXMLDOMNodeList Dim strPath As String Set dom = New DOMDocument30 dom.async = False dom.loadXML &quot;&quot; dom.setProperty &quot;SelectionLanguage&quot;, &quot;XPath&quot; strPath = &quot;/Admin/Area[string-length(@AreaName) = 1]&quot; Set nodelist = dom.documentElement.selectNodes(strPath) Debug.Print &quot;Found &quot; & nodelist.length & &quot; Node&quot;  Run the application, and note that the Immediate window shows Found 1 Node. To show the default behavior, comment out the code line that calls setProperty. Running the code then produces an error message because XSL pattern-matching does not support the string-length function.</li></ol>

NOTE:
 * With MSXML version 2.6, you need to make a reference to Microsoft XML, v2.6 in the Visual Basic project, and then use the corresponding ProgID of DOMDocument26.
 * If a newer version of MSXML has been installed in Side-by-Side mode, then to run the sample code with that specific version, you must explicitly use the GUIDs or ProgIDs for that version. For example, MSXML version 4 only installs in side-by-side mode. Please refer to the following article in the Microsoft Knowledge Base to see what code changes required to run the sample code with MSXML 4.0 parser: Q305019 INFO: MSXML 4.0 Specific GUIDs and ProgIds. That is, with MSXML version 4.0, make a reference to Microsoft XML, v4.0 in the Visual Basic project, and then use the corresponding ProgID of DOMDocument40.
 * When programming with Microsoft Visual C++, the setProperty method is only available with IXMLDOMDocument2 interface.
 * For simplicity, the previous code does not include error checking. It is always a good practice to catch and handle errors.

<div class="references_section">