Working with XML Data


HTTP-based Web services frequently use Extensible Markup Language (XML) messages to return data back to the client. In some cases, the returned XML follows a standard format (or schema), for example SOAP message format. For more information, see Building and Accessing Services Using Proxies.

In other cases, the service developer defines a custom schema for use by the service and client, sometimes referred to as Plain Old XML (POX).

Assume that after making a request to the HTTP-based Web service as described in How to: Make Requests to HTTP-Based Services, the following XML is returned inside a responseStream object of type Stream.

<User IsMember="true">

Here are three techniques available in Silverlight version 4 to parse this response.

Using XmlReader

This code uses XmlReader.

XmlReader responseReader = XmlReader.Create(responseStream);

bool isMember = Boolean.Parse(responseReader.GetAttribute("IsMember")); responseReader.Read();

string name = responseReader.ReadContentAsString();

int age = responseReader.ReadContentAsInt();


For more information, see How to: Parse XML with XmlReader.


This code uses the XLINQ.

XmlReader responseReader = XmlReader.Create(responseStream);
XElement user = XElement.Load(responseReader);

bool isMember = (bool)user.Attribute("IsMember");
string name = (string)user.Element("Name");
int age = (int)user.Element("Age");

For more information, see Processing XML Data with LINQ to XML.

Using XmlSerializer

XML data can also be deserialized into a complex CLR type, where the mapping from XML elements/attributes to object properties is controlled by the application developer. The following CLR type is created and use the XmlElementAttribute and XmlAttributeAttribute to ensure that the names of elements and attributes match those in the XML.

public class User
    public bool IsMember { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }

Then XmlSerializer is invoked to deserialize the XML into an instance of the User class.

XmlSerializer serializer = new XmlSerializer(typeof(User));
User user = (User)serializer.Deserialize(responseStream);
bool isMember = user.IsMember;
string name = user.Name;
int age = user.Age;

See Also

Community Additions