Microsoft KB Archive/303516

= How To Use the starts-with XPath Function =

Article ID: 303516

Article Last Modified on 8/30/2004

-

APPLIES TO


 * Microsoft XML Core Services 4.0
 * Microsoft XML Parser 3.0 Service Pack 1

-



This article was previously published under Q303516



SUMMARY
It is a common programming requirement when you load and parse an XML document using the Microsoft XML (MSXML) Document Object Model (DOM) to identify elements and/or elements with attributes whose values begin with a specific character or sequence of characters. This article includes a code sample that demonstrates how you can use the starts-with XML Path Language (XPath) string function to implement this requirement.



Step-by-Step Example
  In Notepad, create a new XML document named Books.xml, and paste the following XML: 

  Joe Bob Trenton Literary Review Honorable Mention 12   Mary Bob</last-name> Selected Short Stories of       Mary</first-name> Bob</last-name> 55                    </li> <li>Save Books.xml in the root folder of drive C.</li> <li>Open a new Standard EXE project in Microsoft Visual Basic. Form1 is created by default.</li> <li>From the Project menu, click References, and then select the Microsoft XML 3.0 check box.</li> <li>Drag a Command button, and drop it onto Form1.</li> <li> Copy and paste the following code in the Click event procedure of the Command button: Dim doc As MSXML2.DOMDocument Dim nlist As MSXML2.IXMLDOMNodeList Dim node As MSXML2.IXMLDOMNode

Set doc = New MSXML2.DOMDocument doc.setProperty &quot;SelectionLanguage&quot;, &quot;XPath&quot; doc.Load &quot;c:\books.xml&quot; Set nlist = doc.selectNodes(&quot;//book/author/first-name[starts-with(.,'M')]&quot;) MsgBox &quot;Matching Nodes : &quot; & nlist.length

For Each node In nlist Debug.Print node.nodeName & &quot; : &quot; & node.Text Next </li> <li>The preceding code loads the XML from Books.xml into an instance of the MSXML DOMDocument object. It then executes an XPath query that uses the starts-with XPath function to identify all authors whose first names begin with the letter M. Finally, the For loop iterates through the selected nodes and displays the first names of the matching author elements.</li> <li>The first parameter of the starts-with XPath function is used to specify the source node or string against which the comparison is to be executed. The second parameter is the pattern string that specifies the character or character sequence that is to be used in the comparison. It is important to remember that the pattern string that is supplied as the second parameter of the starts-with function is case sensitive.</li></ol>

Keywords: kbhowto KB303516

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.