Reputation: 79
I have the following XML schema:
<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>
Using VB, how would I get the value of exactMatch
? I have tried many different methods, but nothing seems to work. Any ideas?
Upvotes: 3
Views: 11266
Reputation: 57956
Try this:
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
Upvotes: 4
Reputation: 189457
Use this code:-
<%
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
Alternatively you may wish only to list those results which are extact matches, in which case you would adjust the code like this:-
Dim result
For Each result in doc.SelectNodes("/lyrics/searchresults/result[@extactMatch='true']")
RenderResult result
Next
BTW, Avoid being tempted by the expedience of '//', if the document structure is known then navigating that structure explicitly is a more robust approach.
Upvotes: 4