2012-04-05 77 views
0

我在http://localhost:8000/Service/我的本地機器上運行的Web服務,當我瀏覽到這一點,以列表格式顯示,像這樣一些硬編碼的信息:XML到列表框從web服務

<ArrayOfStudent> 
<Student> 
<StudentID>bla</StudentID> 
<FirstName>bla</FirstName> 
<LastName>bla</LastName> 
</Student> 
<Student> 
<StudentID>bla1</StudentID> 
<FirstName>bla1</FirstName> 
<LastName>bla1</LastName> 
</Student> 
<Student> 
<StudentID>bla2</StudentID> 
<FirstName>bla2</FirstName> 
<LastName>bla2</LastName> 
</Student> 
</ArrayOfStudent> 

我如何可以採取一個XML列表像這樣,並將其添加到從我的uri http://localhost:8000/Service/列表框,因爲它完成休息我不能添加到Windows窗體應用程序的服務引用?

例如下面教你如何將圖像從一個URI添加到imagebox的方法:

public Image GetImage(int width, int height) 
    { 
     string uri = string.Format("http://localhost:8000/Service/picture/{0}/{1}", width, height); 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 

     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
     { 
      using (Stream stream = response.GetResponseStream()) 
      { 
       return new Bitmap(stream); 
      } 
     } 
    } 

然後,所有我需要做的就是調用pictureBox1.Image = GetImage(pictureBox1.Height, pictureBox1.Width);任何地方我想要的。我只是沒有線索如何從我的服務添加文本數據?

我試圖這樣的事情:http://www.dotnetcodecentral.com/Post/215/wcf-rest-consuming/convert-or-deserialize-wcf-rest-response-to-objects-list

private void button2_Click(object sender, EventArgs e) 
    { 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); 
     HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
     Stream strm = resp.GetResponseStream(); 
     XElement xdoc = XElement.Load(strm); // XElement.Load has some invalid arguements? 
     q = From student In xdoc.<Student>// from here 
      Select New With { 
       .StudentNo = student.<StudentID>.Value, 
       .Firstname = student.<FirstName>.Value, 
       .Surname = student.<LastName>.Value, 
      }; // to here is abit of a mess 
     listBox1.DataSource = q.ToList(); 
    } 
} 

編輯 - 格式化問題?

enter image description here

回答

1
XDocument xDoc = XDocument.Load(url); 
var students = xDoc.Descendants("Student") 
    .Select(n => new 
    { 
     StudentNo = n.Element("StudentID").Value, 
     Firstname = n.Element("FirstName").Value, 
     Surname = n.Element("LastName").Value 
    }) 
    .ToList(); 

dataGridView1.DataSource = students; 
+0

當你說的網址你的意思是我的本地地址?這也意味着我不需要流strm響應線? – 2012-04-05 19:45:38

+0

@Garrith。對,就是這樣。 – 2012-04-05 19:47:13

+0

它的工作原理:)我已經更新了我的問題,它似乎提供了一個格式問題的升技?這是從Windows窗體應用程序或Web服務? – 2012-04-05 19:52:15