Wonderlander
Wonderlander

Reputation: 1

How to serialize a class with a complex property using XML serialization in .NET?

I want to serialize a class. In this class there's a property of type Class1 that in turn has its own properties.

public abstract class ComponentBase
{
    [ToSerialize] //An attribute defined my me, indicating whether or not to serialize this property.
    public ComponentArgs Parameters { get; set; }
}

public class ComponentArgs
{
    public string WorkingPath { get; set; }
    public IList<Language> Languages { get; set; }
    public string ComponentOutputPath { get; set; }
}

The information serialized must be put into a Dictionary<string,string>, such as

ComponentSettings[str_Name] = str_Value;

The method used in reading this value is Reflection

// pinfo: Property Info got via Type.GetProperties();
componentSettings.Add(pinfo.Name, pinfo.GetValue((object)this, null).ToString());

The information after serialization is:

<Parameters>MS.STBIntl.Pippin.Framework.ComponentArgs</Parameters>

instead of the value of ComponentArgs.WorkingPath.

The solution I thought of is to append to the following line an if judgement:

componentSettings.Add(pinfo.Name, pinfo.GetValue((object)this, null).ToString());

if(pinfo is ComponentArgs)
    componentSettings.Add(pinfo.Name, pinfo.GetValue(
        (ComponentArgs)this, null).WorkingPath+"\n"+
        LanguageList+"\n"+ //Language list is a concatinated string of all elements in the list.
        (ComponentArgs)this, null).ComponentOutputPath+"\n"+
    );

When deserializing, add a judgement of whether the value contains more than 2 "\n", if so, extract each value from the string.

But this way seems clumsy and much more like an workaround. I wonder if there's any more professional way of doing it? My reviewer is very particular and he won't accept such a solution. If you know a way, could you please share it with me? Thanks a lot.

Upvotes: 0

Views: 944

Answers (1)

John Nicholas
John Nicholas

Reputation: 4836

There are lots of ways to use inbuilt serialization.

The simplest and oldest is the [Serializable] attribute that tells .NET to serialize the members.

You can also use the WCF [DataContract] attribute to serialize stuff.

There is also the IXMLSerializable interface which allows you to implement custom XML readers and writers for you classes.

The bottom line is, there is no need to roll your own - it has been done.

Upvotes: 1

Related Questions