Stefan Meyer
Stefan Meyer

Reputation: 928

Accessing an item in XMLnodelist using vb.net

I have got a vb.net XML node list, delivered 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>

How kan I acess the Element <text>483 km</text> using vb.net?

This is my code so far:

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

I only want to throw two locations to google maps and get the distance in km between them. If you got another approach I am looking forward seeing it.

Best regards, Stefan

Upvotes: 1

Views: 1826

Answers (1)

Victor Zakharov
Victor Zakharov

Reputation: 26424

Here is a reduced test case example to play with (console app):

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)

In your case, instead of assigning an xml variable with some inline XML, you will be doing XDocument.Parse(responsereader).

Regarding the status check (I am assuming you'd want to convert to LINQ-to-XML completely):

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

Reference:

Upvotes: 1

Related Questions