0
我仍在学习如何使用XML和C#。XML C# - 尝试从xml文档中获取元素列表
我看了很多地方关于如何让这个工作正常,但我无法解决这个问题,并想知道如果任何人都可以看到我要去哪里错了? 我想获得一个列表,其中包含两个单独场合的距离和持续时间的节点值。首先应该只是一对是总分类/持续时间对:/ DirectionsResponse /路线/腿/距离/值,然后我试图得到第二个列表,其中将包含步骤版本:/ DirectionsResponse/route/leg /步骤/距离/值。如果我能得到第二个工作,我可以找出第一个。
非常感谢 Jaie
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();
}
}
太棒了!非常感谢atom.gregg。它现在完美:) – Jaie