Working with XML Data

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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">
    <Name>John</Name>
    <Age>24</Age>
</User>

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

Using XmlReader

This code uses XmlReader.

XmlReader responseReader = XmlReader.Create(responseStream);

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

responseReader.ReadStartElement("Name");
string name = responseReader.ReadContentAsString();
responseReader.ReadEndElement();

responseReader.ReadStartElement("Age");
int age = responseReader.ReadContentAsInt();
responseReader.ReadEndElement();

responseReader.ReadEndElement();

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

Using XLINQ

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
{
    [XmlAttribute]
    public bool IsMember { get; set; }

    [XmlElement]
    public string Name { get; set; }

    [XmlElement]
    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