.NET Framework Xml Serialization Feature

Peace be Upon You,,

Object serialization is an important topic which is quite powerful if used correctly. Serialization allows programs to persist objects by storing them in files. The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa.

I wanted to answer some questions which i was asking when using that feature.

1- How to set Enum value element name in the generated Xml file?

you can that by using the XmlEnum attribute as follows:

[Serializable]

public enum DifficultyLevel

{

[XmlEnum(“very easy”)]

VeryEasy,

[XmlEnum(“easy”)]

Easy,

[XmlEnum(“medium”)]

Medium,

[XmlEnum(“difficult”)]

Difficult,

[XmlEnum(“very difficult”)]

VeryDifficult

}

2- How to set ArrayItem element names?

You can do this by using the XmlArrayItem attribute, example as follows:

public class Library
{
private Book[] books;
[XmlArray(ElementName = “My_Books”)]
[XmlArrayItem(ElementName = “MyBook”)]
public Book[] Books
{
get { return books; }
set { books = value; }
}
}

public class Library

{

private Book[] books;

[XmlArray(ElementName = “My_Books”)]

[XmlArrayItem(ElementName = “MyBook”)]

public Book[] Books

{

get { return books; }

set { books = value; }

}

}

Regards.