2011-09-21 67 views
0

我目前正在使用下面的代碼解析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

感謝。

回答

2

鑑於這種輸出字符串,你可以通過讓你的三個數字:

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