简体   繁体   中英

XML C# - trying to get a List of elements from an xml document

I am still learning to work with XML and C#.

I have looked many places on how to get this to work properly but I am unable to solve this as of yet and was wondering if anyone can see where I am going wrong? I am trying to get a list containing the node values for distance and duration for two seperate occasions. First should be just one pair which is the total dist/duration pair: /DirectionsResponse/route/leg/distance/value, then I'm trying to get a second list which will contain the steps version: /DirectionsResponse/route/leg/steps/distance/value. If I can get the second one working I can figure out the first.

Many Thanks 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();

    }
}

I reckon you are pretty close to where you want to be, just a little debugging would get you over the line.

Here is a small snippet of what I threw together in LinqPad which I use to scratch together things before I commit them to code.

var origin = "Canberra+Australia";
var dest = "sydney+Australia";
var baseUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin={0}&destination={1}&sensor=false&departure_time=1343605500&mode=driving";

var req = string.Format(baseUrl, origin, dest);
var resp = new System.Net.WebClient().DownloadString(req);
var doc = XDocument.Parse(resp);

var total = doc.Root.Element("route").Element("leg").Element("distance").Element("value").Value;
total.Dump();

var steps = (from row in doc.Root.Element("route").Element("leg").Elements("step")
             select new 
             { 
                Duration = row.Element("duration").Element("value").Value,
                Distance = row.Element("distance").Element("value").Value
             }).ToList();
steps.Dump();

The Dump method spits the result out to the LinqPad results. I had a list of 16 items in my steps results, and the total distance was a value of 286372.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM