Ayush
Ayush

Reputation: 42450

Deserializing XML from the web

Generally, this is how I deserialize an XML file:

    string location = "C:\\test.xml";
    XmlObjectClass member_data = new XmlObjectClass();

                using (Stream XmlStream = new FileStream(location,FileMode.Open))
                {
                    data = (XmlObjectClass)serializer.Deserialize(XmlStream);
                }

This works when I'm desrializing an XML file, but what if I want to deserialize an XML that is returned by a web request (i.e. going to a URL)?

Upvotes: 3

Views: 4667

Answers (2)

Ondrej Tucny
Ondrej Tucny

Reputation: 27974

Providing the response is saved in memory, you can use a MemoryStream, a StringReader, or such a class that fits the format of the data and the capabilities of XmlSerializer.Deserialize() method.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504132

Well, there are a few options:

  • Create an XmlReader with XmlReader.Create(uri) and deserialize directly
  • Get the stream from the WebClient or HttpWebRequest, and deserialize from the stream
  • Fetch all the data, then build a stream around it using MemoryStream and deserialize from that

If you don't need to do anything special with the web request - i.e. it's really just a "GET" from a URI - then the first option is probably the simplest.

Upvotes: 8

Related Questions