tags:

views:

213

answers:

1

HI, I have this asp classic app and I am trying to retrieve a single node, but I keep getting an Object Required error. The selectNodeBytags works but returns a node list I just want a single node.

This errors with "Object Required"

 <%
option explicit

Dim xmlDoc

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.async = False

Dim node

If xmlDoc.load(Server.MapPath("vocabulary.xml")) Then  
  xmlDoc.setProperty "SelectionLanguage", "XPath" 

 set node = xmlDoc.selectSingleNode("Word[@type='noun']") 
 Response.write node.text

end if
 %>

This works using getElementsByTagName

<%
option explicit

Dim xmlDoc

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.async = False

Dim node

If xmlDoc.load(Server.MapPath("vocabulary.xml")) Then  
  xmlDoc.setProperty "SelectionLanguage", "XPath" 

   ' Grabs the elements in each "word" element 
   Dim nodelist
   Set nodelist = xmlDoc.getElementsByTagName("Word")   

   for each node in nodelist
     Response.write(node.nodeName) & "<br />"   'Returns parent node name
  Response.write(node.text) & "<br />"
   next
 end if 

 %>

xml file I am using

   <?xml version="1.0" encoding="utf-8" ?> 
<Vocabulary>
   <Word type="noun" level="1">
      <English>cat</English>
      <Spanish>gato</Spanish>
   </Word>
   <Word type="verb" level="1">
      <English>speak</English>
      <Spanish>hablar</Spanish>
   </Word>
   <Word type="adj" level="1">
      <English>big</English>
      <Spanish>grande</Spanish>
   </Word>
</Vocabulary>
+2  A: 

Try :-

set node = xmlDoc.selectSingleNode("/Vocabulary/Word[@type='noun']") 

XPath by default only selects elements the are direct childern of the node against which it is executing. The document itself is a node and only ever has one element child (in this case the "Vocabulary" node). Hence you need a "path" to select first the top node then the required node below that. The following is an equivalent in this case:-

set node = xmlDoc.documentElement.selectSingelNode("Word[@type='noun']")
AnthonyWJones
After I spent hours playing around with this I found out the select needs a full path to the node whereas the elementsbytag does not. So in your example the first one would work, but he second will not.
chobo
@chobo: Interesting, did you try the second example (bar the obvious typo) ? `selectSingleNode`, as stated, is a path from the current node, so yes if the current node is the document itself you will need a full path. However if the current node is something deeper within the document you will only need a relative one. Using `documentElement` makes the `Vocabulary` node the current node hence the relative path I use in the second example is correct and does actually work.
AnthonyWJones