This code shows how to deserialize a string containing xml to an object using a StringReader and an XmlTextReader (remember to insert a using-statement, where appropiate). The deserialized class also shows how to handle xml-arrays using the serialization attributes.
// ===============================================================================
// Copyright (C) 2005 Paul van Brenk
// All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
// ==============================================================================
// Deserializing a string containing xml and an xml-array.
// ==============================================================================
using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class MyClass
{
public static void Main()
{
string xml = "<person>" +
"<firstname>Paul</firstname>" +
"<lastname>van Brenk</lastname>" +
"<addresses>" +
" <address>" +
" <street>Home Street</street>" +
" <number>80</number>" +
" <postalcode>1000 AA</postalcode>" +
" <city>Home Town</city>" +
" <country>The Netherlands</country>" +
" </address>" +
" <address>" +
" <street>Work Street</street>" +
" <number>100</number>" +
" <postalcode>1000 BB</postalcode>" +
" <city>Work Town</city>" +
" <country>The Netherlands</country>" +
" </address>" +
"</addresses>" +
"</person>";
XmlSerializer ser = new XmlSerializer( typeof(Person) );
StringReader reader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(reader);
Person person = (Person)ser.Deserialize(xmlReader);
}
}
[XmlRoot("person")]
public class Person{
public Person(){
// required for serializer
}
[XmlElement("firstname")]
public string FirstName;
[XmlElement("lastname")]
public string LastName;
//defines the arraynode
[XmlArray("addresses")]
// defines the node in the array
[XmlArrayItem("address")]
public Address[] Addresses{
get{
if(this.addresses == null ){
return new Address[0];
}
return this.addresses;
}
set{
this.addresses = value;
}
}
[XmlAnyElement()]
public XmlElement[] UnknownElements;
private Address[] addresses;
}
// this attribute has no influence on the rendering
// of the element as part of an Xml-array.
[XmlRoot("address")]
public class Address{
public Address(){
// required for serializer
}
[XmlElement("street")]
public string Street;
[XmlElement("number")]
public int Number;
[XmlElement("postalcode")]
public string PostalCode;
[XmlElement("city")]
public string City;
[XmlElement("country")]
public string Country;
}