2010-02-06 20 views
2

嗨,我有這個asp經典的應用程序,我試圖檢索單個節點,但我不斷收到一個對象所需的錯誤。 selectNodeBytags工作,但返回一個節點列表,我只想要一個節點。getElementByTag的作品,但選擇單節點不

與此錯誤 「必選對象」

<% 
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 
%> 

這個工程使用的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文件,我使用

<?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> 

回答

4

嘗試: -

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

默認情況下,XPath只選擇它正在執行的節點的直接childern元素。文檔本身是一個節點,並且只有一個元素子節點(在本例中爲「詞彙表」節點)。因此,您需要一個「路徑」來首先選擇頂部節點,然後選擇下面的所需節點。以下是在這種情況下的等價物: -

set node = xmlDoc.documentElement.selectSingelNode("Word[@type='noun']") 
+0

我花了幾個小時玩這個後,我發現選擇需要一個完整的路徑到節點而elementsbytag沒有。所以在你的例子中,第一個可以工作,但是第二個不會。 – chobo 2010-02-06 19:03:48

+0

@chobo:有意思,你是否嘗試過第二個例子(禁止明顯的錯字)?如上所述,'selectSingleNode'是當前節點的路徑,所以如果當前節點是文檔本身,則需要一個完整路徑。但是,如果當前節點在文檔內更深處,則只需要一個相對的節點。使用'documentElement'使'Vocabulary'節點成爲當前節點,因此我在第二個例子中使用的相對路徑是正確的,並且確實有效。 – AnthonyWJones 2010-02-06 20:39:09