text
stringlengths
0
13.4k
public class Dog
{
private const string _birthStringFormat = "yyyy-MM-dd";
[XmlIgnore]
public DateTime Birth {get; set;}
[XmlElement(ElementName="Birth")]
public string BirthString
{
get { return Birth.ToString(_birthStringFormat); }
set { Birth = DateTime.ParseExact(value, _birthStringFormat, CultureInfo.InvariantCulture);
}
}
}
Section 34.2: Serialize object
public void SerializeFoo(string fileName, Foo foo)
{
var serializer = new XmlSerializer(typeof(Foo));
using (var stream = File.Open(fileName, FileMode.Create))
{
serializer.Serialize(stream, foo);
}
}
Section 34.3: Deserialize object
public Foo DeserializeFoo(string fileName)
{
var serializer = new XmlSerializer(typeof(Foo));
using (var stream = File.OpenRead(fileName))
{
return (Foo)serializer.Deserialize(stream);
}
}
Section 34.4: Behaviour: Map array name to property
(XmlArray)
<Store>
<Articles>
<Product/>
<Product/>
</Articles>
</Store>
public class Store
{
[XmlArray("Articles")]
GoalKicker.com – .NET Framework Notes for Professionals
111
public List<Product> Products {get; set; }
}
Section 34.5: Behaviour: Map Element name to Property
<Foo>
<Dog/>
</Foo>
public class Foo
{
// Using XmlElement
[XmlElement(Name="Dog")]
public Animal Cat { get; set; }
}
Section 34.6: Eciently building multiple serializers with
derived types specified dynamically
Where we came from
Sometimes we can't provide all of the required metadata needed for the XmlSerializer framework in attribute.
Suppose we have a base class of serialized objects, and some of the derived classes are unknown to the base class.
We can't place an attribute for all of the classes which are not know at the design time of the base type. We could
have another team developing some of the derived classes.
What can we do
We can use new XmlSerializer(type, knownTypes), but that would be a O(N^2) operation for N serializers, at least
to discover all of the types supplied in arguments:
// Beware of the N^2 in terms of the number of types.
var allSerializers = allTypes.Select(t => new XmlSerializer(t, allTypes));
var serializerDictionary = Enumerable.Range(0, allTypes.Length)
.ToDictionary (i => allTypes[i], i => allSerializers[i])
In this example, the the Base type is not aware of it's derived types, which is normal in OOP.
Doing it efficiently