xml to listbox from webservice

2019-09-02 04:56发布

问题:

I have a web service running on my local machine at http://localhost:8000/Service/ when I navigate to this it displays some hardcoded information in list format like so:

<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>

How can I take a xml list like this and add it to a listbox from my uri http://localhost:8000/Service/ as its done with rest I cant add in a service reference to the windows form app?

For instance here is a method on how to add an image to an imagebox from a 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);
            }
        }
    }

Then all I have to do is call pictureBox1.Image = GetImage(pictureBox1.Height, pictureBox1.Width); anywhere I want. I just dont have a clue how to add text data from my service?

I was attempting something like this: 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();
    }
}

EDIT - Formatting issue?

回答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;