I am trying to read xml nodes values from lastfm web service that look like this:
<lfm status="ok">
<results for="stinkfist" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
<opensearch:Query role="request" searchTerms="stinkfist" startPage="1" />
<opensearch:totalResults>188</opensearch:totalResults>
<opensearch:startIndex>0</opensearch:startIndex>
<opensearch:itemsPerPage>1</opensearch:itemsPerPage>
<trackmatches>
<track>
<name>Stinkfist</name>
<artist>Tool</artist>
<url>http://www.last.fm/music/Tool/_/Stinkfist</url>
<streamable fulltrack="0">1</streamable>
<listeners>290583</listeners>
<image size="small">http://userserve-ak.last.fm/serve/34s/24508457.jpg</image>
<image size="medium">http://userserve-ak.last.fm/serve/64s/24508457.jpg</image>
<image size="large">http://userserve-ak.last.fm/serve/126/24508457.jpg</image>
<image size="extralarge">http://userserve-ak.last.fm/serve/300x300/24508457.jpg</image>
<mbid></mbid>
</track>
</trackmatches>
</results>
</lfm>
After searching here and on the web for examples i found a way that should work:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim doc As XmlDocument
Dim ns As XmlNamespaceManager
Dim nodes As XmlNodeList
doc = New XmlDocument()
doc.Load("http://ws.audioscrobbler.com/2.0/?method=track.search&limit=1&track=stinkfist&artist=tool&api_key=b25b959554ed76058ac220b7b2e0a026")
ns = New XmlNamespaceManager(doc.NameTable)
ns.AddNamespace("lastfm", "http://a9.com/-/spec/opensearch/1.1/")
nodes = doc.SelectNodes("lastfm:results/lastfm:trackmatches/lastfm:track", ns)
Dim str As String = String.Empty
For Each node As XmlNode In nodes
str += node.Attributes("name").InnerText
str += node.Attributes("artist").InnerText
str += node.Attributes("url").InnerText
str += node.Attributes("listeners").InnerText
Next
Response.Write(str)
End Sub
But when i run the page i get no results the page is empty…
what am i doing wrong?
There are a couple of issues that I see.
First, you don’t need to add the namespace
lastfmonlyopensearch(if you need to access those elements).So this line:
Would become:
If you needed to access the
opensearchelements you would then use it like:To select the
tracknodes your XPath query should be:The track nodes do not have attributes, so
node.Attributes("name").InnerTextwill not work. Rather, they have child elements (nodes), so to get those values you can do:or even shorter syntax
Putting it all together, your program would resemble the following:
Lastly, MSDN has very good examples of using XPath and XmlDocument, which you may find useful.