如何使用字符串拆分将其转换为Lat,Long和Alt?

问题描述:

我目前正在使用下面的代码解析XML文件以获取坐标值。如何使用字符串拆分将其转换为Lat,Long和Alt?

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) 
     { 

      WebClient busStops = new WebClient(); 
      busStops.DownloadStringCompleted += new DownloadStringCompletedEventHandler(busStops_DownloadStringCompleted); 
      busStops.DownloadStringAsync(new Uri("http://www.location.com/file.xml")); 


     } 


     void busStops_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      if (e.Error != null) 
       return; 



      var busStopInfo = XDocument.Load("Content/BusStops2.xml"); 

      var Transitresults = from root in busStopInfo.Descendants("Placemark") 
           let StoplocationE1 = root.Element("Point").Element("coordinates") 
           let nameE1 = root.Element("name") 


           select new TansitVariables 

           { 

            Stoplocation = StoplocationE1 == null ? null : StoplocationE1.Value, 
            name = nameE1 == null ? null : nameE1.Value, 

           }; 


      listBox2.ItemsSource = Transitresults; 

     } 

     public class TansitVariables 
     { 
      public string Stoplocation { get; set; } 
      public string name { get; set; } 

     } 


    } 

} 

该值在String StopLocation中,但我想将其转换为3个值Lat,Long和Alt。

我没有使用过之前的字符串分割和文档没有解释如何我可以从解析输出做到这一点。

Out是提前这174.732224,-36.931053,0.000000

感谢。

鉴于这种输出字符串,你可以通过让你的三个数字:

string result = "174.732224,-36.931053,0.000000"; 

var items = result.Split(','); 
double longitude = double.Parse(items[0]); 
double latitude = double.Parse(items[1]); 
double altitude = double.Parse(items[2]); 

编辑:

你的代码,将需要改变部分可能是:

var Transitresults = from root in busStopInfo.Descendants("Placemark") 
       let StoplocationE1 = root.Element("Point").Element("coordinates") 
       let nameE1 = root.Element("name") 
       select new TansitVariables(
         StoplocationE1 == null ? null : StoplocationE1.Value, 
         nameE1 == null ? null : nameE1.Value); 

    listBox2.ItemsSource = Transitresults; 
} 

// Add properties to your class 
public class TransitVariables 
{ 
     // Add a constructor: 
     public TransitVariables(string stopLocation, string name) 
     { 
      this.StopLocation = stopLocation; 
      this.Name = name; 
      if (!string.IsNullOrWhiteSpace(stopLocation)) 
      { 
       var items = stopLocation.Split(','); 
       this.Lon = double.Parse(items[0]); 
       this.Lat = double.Parse(items[1]); 
       this.Alt = double.Parse(items[2]); 
      } 
     } 

     public string StopLocation { get; set; } 
     public string Name { get; set; } 
     public double Lat { get; set; } 
     public double Lon { get; set; } 
     public double Alt { get; set; } 
} 
+0

谢谢里德,问题是有多个StopLocations,我需要将它们全部转换为绑定到Bing图钉位置 – Rhys

+0

@Rhys:上面的代码应该工作 - 只是做一个方法,做这种转换,并在您的查询中调用它来设置值... –

+0

我不知道如何将它实现到我的代码。任何机会,你可以编辑我的代码,并告诉我?对不起,我是一个痛苦的人,我一直试图得到这个数周,并受到我缺乏C#知识的限制。 – Rhys