2009-05-05 37 views
1

我有一些非常簡單的XML:查詢XML沒有XSL

<properties> 
<property> 
    <name>BobFish</name> 
    <explaination>Bob is a fish.</explaination> 
</property> 
<property> 
    <name>DaveFish</name> 
    <explaination>Dave is a fish.</explaination> 
</property> 

我想從ASP如果查詢。喜歡的東西:

Response.Write (GetExplaination("BobFish")) 

這是我迄今爲止功能:

Function GetExplaination(strXMLFile, strName) 

'Declare local variables 
Dim objXML 
Dim objNode 

set objXML = Server.CreateObject("Microsoft.XMLDOM") 
objXML.load(strXMLFile) 
Set objNode = objXML.SelectSingleNode("properties/property[name='" & strName & "']") 

    GetExplaination = "Nothing Yet" 

End Function 

所以我有一個包含我所需要的數據objNode。我如何從中提取「解釋」字段?

回答

2
Function GetExplaination(strXMLFile, strName) 
    Dim objXML 
    Dim objNode 
    Dim strXPath 

    Set objXML = CreateObject("Microsoft.XMLDOM") 
    objXML.load(strXMLFile) 

    ''// enclose in single- or double quotes accordingly 
    If InStr(strName, "'") > 0 And InStr(strName, """") = 0 Then 
    strName = """" & strName & """" 
    ElseIf InStr(strName, "'") = 0 And InStr(strName, """") > 0 Then 
    strName = "'" & strName & "'" 
    Else 
    ''// both single and double quotes in a string are unsupported 
    strName = "''" 
    End If 

    strXPath = "/properties/property[name = " & strName & "]/explaination" 
    Set objNode = objXML.SelectSingleNode(strXPath) 

    If Not objNode Is Nothing Then 
    GetExplaination = objNode.Text 
    End If  
End Function 

...

Response.Write GetExplaination("Fish.xml", "DaveFish") 

我不會建議每加載文檔當你尋找一個單一的財產。預先加載並解析文檔,並將文檔引用傳遞給函數,而不是文件路徑。

+0

非常感謝。 – theaxe 2009-05-05 16:56:35

2

首先添加一個路徑到您的解釋節點來獲取,而不是整個屬性節點。

Set objNode = objXML.SelectSingleNode("properties/property[name='" & strName & "']/explanation") 

下一頁返回節點的innerText讓你的文字後

GetExplaination = objNode.Text 
+0

我不好,謝謝,修好了 – 2009-05-05 11:49:19