.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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s