使用ASP / VB获取节点属性的值

时间:2010-02-09 00:40:01

标签: xml dom asp-classic vbscript

我有以下XML架构:

 <lyrics>
      <response code="0">SUCCESS</response>
      <searchResults>
           <result id="120745" hid="gXTQx5ywE0M=" exactMatch="true">
                <title>Opera Singer</title>
                <artist>
                     <name>Cake</name>
                </artist>
           </result>
      </searchResults>
 </lyrics>

使用VB,我如何获得exactMatch的值?我尝试过很多不同的方法,但似乎没什么用。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

试试这个:

Set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
    xmldoc.async = true
    xmldoc.Load Server.MapPath("yourfile.xml")

'' // query for a specific result        
Set result = xmldoc.SelectSingleNode("//result[@id='120745']")
Response.Write(result.GetAttribute("exactMatch") & "<br />")

'' // get all results elements
Set results = xmldoc.SelectNodes("//result")
For Each result In results
    Response.Write(result.GetAttribute("exactMatch") & "<br />")
Next

答案 1 :(得分:4)

使用此代码: -

<%
Option Explicit
Dim doc: Set doc = YourFunctionThatFetchesTheResults()

Dim result
For Each result in doc.SelectNodes("/lyrics/searchresults/result")
   RenderResult result
Next

Sub RenderResult(result)
   Dim ID : ID = result.getAttribute("ID")
   Dim exactMatch : ID = result.getAttribute("extactMatch")
   Dim title : title = GetElemText(result,"title")
   Dim artist : artist = GetElemText(result, "artist/name")
   %>
   <tr><td><%=ID%></td><td><%=exactMatch%></td><td><%=title%></td><td><%=artist ></td></tr>
   <%
End Sub

Function GetElemText(node, path)
    Dim elem : Set elem = node.selectSingleNode(path)
    If Not elem is Nothing Then
        GetElemText = elem.Text
    End If
End Function

或者你可能只希望列出那些是extact匹配的结果,在这种情况下你可以像这样调整代码: -

Dim result
For Each result in doc.SelectNodes("/lyrics/searchresults/result[@extactMatch='true']")
   RenderResult result
Next
顺便说一下,如果知道文档结构,那么避免被'//'的权宜所诱惑,那么明确地导航该结构是一种更强大的方法。