1

我有一个 vb.net XML 节点列表,由 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>

我如何<text>483 km</text>使用 vb.net 访问元素?

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

    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 :) #####

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

最好的问候,斯特凡

4

1 回答 1

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您将使用XDocument.Parse(responsereader).

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

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

参考:

于 2014-06-16T15:30:16.390 回答