来自webservice的xml到listbox

时间:2012-04-05 18:11:03

标签: c# wcf web-services rest

我在http://localhost:8000/Service/的本地计算机上运行了一个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添加图像到图像框的方法:

    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 个答案:

答案 0 :(得分: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;