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