使用vb.net访问XMLnodelist中的项目

时间:2014-06-16 09:30:21

标签: vb.net xmlnodelist

我有一个vb.net XML节点列表,已发送from goolle maps api

<?xml version="1.0" encoding="UTF-8"?>
<DistanceMatrixResponse>
  <status>OK</status>
  <origin_address>Dusseldorf, Germany</origin_address>
  <destination_address>Wiesenburg, Germany</destination_address>
  <row>
    <element>
      <status>OK</status>
      <duration>
        <value>15931</value>
        <text>4 hours 26 mins</text>
      </duration>
      <distance>
        <value>482793</value>
        <text>483 km</text>
      </distance>
    </element>
  </row>
</DistanceMatrixResponse>

我是如何使用vb.net获取元素<text>483 km</text>的?

到目前为止,这是我的代码:

    Dim URL As String = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + origin + "&destinations=" + destination + "&mode=driving&sensor=false&language=en-EN&units=km"
    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(URL), HttpWebRequest)
    Dim response As WebResponse = request.GetResponse()
    Dim dataStream As Stream = response.GetResponseStream()
    Dim sreader As New StreamReader(dataStream)
    Dim responsereader As String = sreader.ReadToEnd()
    response.Close()

    Dim xmldoc As New XmlDocument()
    xmldoc.LoadXml(responsereader)


    If xmldoc.GetElementsByTagName("status")(0).ChildNodes(0).InnerText = "OK" Then

    '##### here comes "Your" code :) #####

我只想将两个位置投射到谷歌地图并获得它们之间的距离。如果你有另一种方法,我很期待看到它。

祝你好运, 斯蒂芬

1 个答案:

答案 0 :(得分:1)

这是一个简化的测试用例示例(控制台应用程序):

Dim xml As XDocument =
  <?xml version="1.0" encoding="UTF-8"?>
  <DistanceMatrixResponse>
    <status>OK</status>
    <origin_address>Dusseldorf, Germany</origin_address>
    <destination_address>Wiesenburg, Germany</destination_address>
    <row>
      <element>
        <status>OK</status>
        <duration>
          <value>15931</value>
          <text>4 hours 26 mins</text>
        </duration>
        <distance>
          <value>482793</value>
          <text>483 km</text>
        </distance>
      </element>
    </row>
  </DistanceMatrixResponse>

Dim textElement As XElement =
  xml.Descendants("distance").Elements("text").First()
Console.WriteLine(textElement.Value)

在您的情况下,您将执行xml,而不是使用内联XML分配XDocument.Parse(responsereader)变量。

关于状态检查(我假设你想完全转换为LINQ-to-XML):

If xml.Root.Element("status").Value = "OK" Then

参考: