Reputation: 6122
This is the XML response I'm trying to parse:
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://www.webserviceX.NET/">0.7627</double>
The VB code:
Dim responseString As String
Dim fromCurrency As String = "EUR"
Dim toCurrency As String = "USD"
Dim req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=" & fromCurrency & "&ToCurrency=" & toCurrency)
Dim Resp As System.Net.HttpWebResponse = req.GetResponse()
Dim reader As StreamReader = New StreamReader(Resp.GetResponseStream)
responseString = reader.ReadToEnd()
'get the XML
Dim objXML As New XmlDocument
objXML.LoadXml(responseString)
Dim root As XmlNode = objXML.DocumentElement
Dim nodeList As XmlNodeList = root.SelectNodes("/double")
How can I read the result value of "0.7627"?
I tried:
nodeList(0).InnerText
and
nodeList(0).SelectSingleNode("/double").InnerText
Both throw the error "Object reference not set to an instance of an object."
I also tried adding a namespace manager:
Dim mgr As XmlNamespaceManager = New XmlNamespaceManager(objXML.NameTable)
mgr.AddNamespace("currency", objXML.DocumentElement.NamespaceURI)
Dim node As XmlNode = objXML.SelectSingleNode("double", mgr)
And select via:
node.InnerText
But that also throws "Object reference not set to an instance of an object."
Upvotes: 2
Views: 2897
Reputation: 125620
You can try using LINQ to XML:
Imports System.XML.Linq
(...)
Dim req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=" & fromCurrency & "&ToCurrency=" & toCurrency)
Dim Resp As System.Net.HttpWebResponse = req.GetResponse()
Dim doc as XDocument = XDocument.Load(Resp.GetResponseStream)
Dim myDoubleValue as Double = CDbl(doc.Root)
myDoubleValue
should be 0.7627
Upvotes: 0
Reputation: 40526
Here are the problems I see with the code:
you need to correctly define the namespace (it's the one in the XML: "http://www.webserviceX.NET/"
)
you need to use the namespace in the XPath expression you pass to SelectSingleNode
Here's how I did it (using C#):
var namespaceManager = new XmlNamespaceManager(objXML.NameTable);
namespaceManager.AddNamespace("wsx", "http://www.webserviceX.NET/");
var doubleNode = root.SelectSingleNode("/wsx:double", namespaceManager);
Console.WriteLine(doubleNode.InnerText);
Here's the VB.NET equivalent (I hope it's right, I converted the code using a tool):
Dim namespaceManager = New XmlNamespaceManager(objXML.NameTable)
namespaceManager.AddNamespace("wsx", "http://www.webserviceX.NET/")
Dim doubleNode = root.SelectSingleNode("/wsx:double", namespaceManager)
Console.WriteLine(doubleNode.InnerText)
Upvotes: 3