从ASP查询xml而不使用XSL

时间:2009-05-05 11:19:03

标签: xml asp-classic

我有一些非常简单的XML:

<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 个答案:

答案 0 :(得分:2)

首先添加一个到解释节点的路径来获取它而不是整个属性节点。

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

接下来返回节点的innertext以获取您之后的文本

GetExplaination = objNode.Text

答案 1 :(得分: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")

我不建议您每次查找单个属性时加载文档。预先加载并解析文档,并将文档引用传递给函数而不是文件路径。