从谷歌距离矩阵API c#读取值
本文关键字:读取 API 谷歌 距离 | 更新日期: 2023-09-27 18:18:31
我有以下来自Google的XML数据包。
<?xml version="1.0" encoding="UTF-8" ?>
- <DistanceMatrixResponse>
<status>OK</status>
<origin_address>Poplar Drive, Kingsbridge, Devon TQ7 1SF, UK</origin_address>
<destination_address>1 Saint Michaels Road, Kingsteignton, Newton Abbot, Devon TQ12 3AQ, UK</destination_address>
- <row>
- <element>
<status>OK</status>
- <duration>
<value>2710</value>
<text>45 mins</text>
</duration>
- <distance>
<value>37958</value>
<text>38.0 km</text>
</distance>
</element>
</row>
</DistanceMatrixResponse>
现在我要做的是将这两个值字段赋值给变量。
我已经把它拉到一个流IE。
Stream stream = client.OpenRead("http://ho-www/GoogleApiAccess/DistanceMatrix.aspx?origins=" + orilat + "," + orilong + "&destinations=" + destlat + "," + destlong + "&mode=driving'&units=imperial'&language=en'&sensor=false' (http://ho-www/GoogleApiAccess/DistanceMatrix.aspx?origins=" + orilat + "," + orilong + "&destinations=" + destlat + "," + destlong + "&mode=driving%27&units=imperial%27&language=en%27&sensor=false%27)");
到目前为止,我所搜索的一切都只告诉我如何获得父元素,即持续时间和距离,但不告诉我如何获得下面的
这应该是一个简单的答案,但我就是想不明白…
有谁能帮我摆脱痛苦吗?有几种方法可以完成您的要求,我不知道您更熟悉哪种方法。这就是为什么我让你把你现在的代码发过来。
另一个答案已经演示了使用XmlDocument
和XPath选择器语法的一种方法。这是使用LINQ-to-XML的XDocument
和方法链语法的另一种可能的方法:
var doc = XDocument.Load(stream);
var duration = (string)doc.Root
.Element("row")
.Element("element")
.Element("duration")
.Element("value");
var distance = (string)doc.Root
.Element("row")
.Element("element")
.Element("distance")
.Element("value");
尝试使用XPath
var xmldoc = new XmlDocument();
xmldoc.Load(stream);
var durationValueNode = xmldoc.SelectSingleNode("//duration/value");
var durationValue = durationValueNode ==null ? "" : durationValueNode.InnerText;
var distanceValueNode = xmldoc.SelectSingleNode("//distance/value");
var distanceValue = distanceValueNode == null ? "" : distanceValueNode.InnerText;