开发者

getElementByTag works but selectsinglenode does not

开发者 https://www.devze.com 2022-12-19 21:04 出处:网络
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.

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>
      &l开发者_C百科t;Spanish>hablar</Spanish>
   </Word>
   <Word type="adj" level="1">
      <English>big</English>
      <Spanish>grande</Spanish>
   </Word>
</Vocabulary>


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']")
0

精彩评论

暂无评论...
验证码 换一张
取 消