2014-02-25 41 views
2

我已經做了一個網絡API,併成功我JSON格式獲取數據,但是當我感到困惑如何獲取XML並在編程中使用 學生班級消費XML的WebAPI

namespace StudentInfoClient2 
{ 
    class Student 
    { 
     public int Id 
     { 
      get; 
      set; 
     } 
     public string FName 
     { 
      get; 
      set; 
     } 
     public string LName 
     { 
      get; 
      set; 
     } 
     public string Gender 
     { 
      get; 
      set; 
     } 
     public string Course 
     { 
      get; 
      set; 
     } 
     public string Email 
     { 
      get; 
      set; 
     } 
     public long PhoneNo 
     { 
      get; 
      set; 
     } 


    } 
} 

程序類

namespace StudentInfoClient2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("The following is the result of Json Data.."); 
      Method1(); 
      Console.WriteLine("\n\n\n"); 
      Console.WriteLine("The following is the result of xml Data..."); 
      Method2(); 

     } 
     static void Method1() 
     { 
      using (HttpClient client = new HttpClient()) 
      { 
       List<Student> studlist = new List<Student>(); 
       client.BaseAddress = new Uri("http://tanmayservice01.sitecloud.cytanium.com/"); 
       client.DefaultRequestHeaders.Accept.Clear(); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

       HttpResponseMessage response = client.GetAsync("api/StudentInfo").Result; 
       if (response.IsSuccessStatusCode) 
       { 
        studlist = response.Content.ReadAsAsync<List<Student>>().Result; 
        foreach (Student s in studlist) 
        { 
         Console.WriteLine("{0}\t{1}\t{2}\t{3}", s.Id, s.FName, s.LName, s.Email); 
        } 
       } 
      } 
     } 
     static void Method2() 
     { 
      using (HttpClient client = new HttpClient()) 
      { 
       client.BaseAddress = new Uri("http://tanmayservice01.sitecloud.cytanium.com/"); 
       client.DefaultRequestHeaders.Accept.Clear(); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); 

       HttpResponseMessage response = client.GetAsync("api/StudentInfo").Result; 
       if (response.IsSuccessStatusCode) 
       { 
        // string strxml = response.Content.ReadAsStringAsync().Result; 
        XDocument doc = XDocument.Load(response.Content.ReadAsStreamAsync().Result); 
        List<Student> studlist = new List<Student>(); 
        Console.WriteLine(doc.ToString()); 

       //Linq query iam looking for 




       } 
      } 
     } 
    } 
} 

如何編寫一個Linq查詢以獲得與我在json中顯示的結果相同的結果?

+0

聽起來像主要的鬥爭是如何將xml結果映射到'Student'類? –

回答

0

爲什麼不直接使用與JSON相同的XML客戶端代碼?

例如

 studlist = response.Content.ReadAsAsync<List<Student>>().Result; 
     foreach (Student s in studlist) 
     { 
      Console.WriteLine("{0}\t{1}\t{2}\t{3}", s.Id, s.FName, s.LName, s.Email); 
     } 

在這兩種情況下,你都有序列化的對象,無論序列化是用花括號還是尖括號都沒有區別。

+0

感謝Darrel的回答..其實我正在尋找linq查詢來獲取xml數據 –