2

这是我试图解析的 XML 响应:

<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://www.webserviceX.NET/">0.7627</double>

VB代码:

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")

如何读取“0.7627”的结果值?

我试过:

nodeList(0).InnerText

nodeList(0).SelectSingleNode("/double").InnerText

两者都抛出错误“对象引用未设置为对象的实例”。

我还尝试添加一个命名空间管理器:

Dim mgr As XmlNamespaceManager = New XmlNamespaceManager(objXML.NameTable)
mgr.AddNamespace("currency", objXML.DocumentElement.NamespaceURI)

Dim node As XmlNode = objXML.SelectSingleNode("double", mgr)

并通过以下方式选择:

node.InnerText

但这也会引发“对象引用未设置为对象的实例”。

4

2 回答 2

3

以下是我在代码中看到的问题:

  • 您需要正确定义名称空间(它是 XML 中的名称"http://www.webserviceX.NET/":)

  • 您需要在传递给的 XPath 表达式中使用命名空间SelectSingleNode

这是我的做法(使用 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);

这是等效的 VB.NET(我希望它是正确的,我使用工具转换了代码):

Dim namespaceManager = New XmlNamespaceManager(objXML.NameTable)
namespaceManager.AddNamespace("wsx", "http://www.webserviceX.NET/")

Dim doubleNode = root.SelectSingleNode("/wsx:double", namespaceManager)

Console.WriteLine(doubleNode.InnerText)
于 2013-02-25T20:22:51.310 回答
0

您可以尝试使用 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应该是 0.7627

于 2013-02-25T20:23:02.783 回答