我仍在学习使用 XML 和 C#。
我已经看过很多关于如何让它正常工作的地方,但我还无法解决这个问题,并且想知道是否有人能看到我哪里出错了?我正在尝试获取一个列表,其中包含两个单独场合的距离和持续时间的节点值。首先应该只是一对,它是总距离/持续时间对:/DirectionsResponse/route/leg/distance/value,然后我试图获取第二个列表,其中包含步骤版本:/DirectionsResponse/route/leg/步数/距离/值。如果我能让第二个工作,我可以弄清楚第一个。
非常感谢杰伊
public class MyNode
{
public string Distance { get; set; }
public string Duration { get; set; }
}
public class Program
{
static void Main(string[] args)
{
//The full URI
//http://maps.googleapis.com/maps/api/directions/xml?`enter code here`origin=Sydney+australia&destination=Melbourne+Australia&sensor=false
//refer: https://developers.google.com/maps/documentation/webservices/
string originAddress = "Canberra+Australia";
string destinationAddress = "sydney+Australia";
StringBuilder url = new StringBuilder();
//http://maps.googleapis.com/maps/api/directions/xml?
//different request format to distance API
url.Append("http://maps.googleapis.com/maps/api/directions/xml?");
url.Append(string.Format("origin={0}&", originAddress));
url.Append(string.Format("destination={0}", destinationAddress));
url.Append("&sensor=false&departure_time=1343605500&mode=driving");
WebRequest request = HttpWebRequest.Create(url.ToString());
var response = request.GetResponse();
var stream = response.GetResponseStream();
XDocument xdoc = XDocument.Load(stream);
List<MyNode> routes =
(from route in xdoc.Descendants("steps")
select new MyNode
{
Duration = route.Element("duration").Value,
Distance = route.Element("distance").Value,
}).ToList<MyNode>();
foreach (MyNode route in routes)
{
Console.WriteLine("Duration = {0}", route.Duration);
Console.WriteLine("Distance = {0}", route.Distance);
}
stream.Dispose();
}
}