XML-сериализация объектов с конвертом в C #

I need to serialize objects to XML in C#. The objects should be wrapped in an envelope. For that, I've created the following Envelope class:

[XmlInclude(typeof(Person))]
public class Envelope
{
    public string SomeValue { get; set; }
    public object WrappedObject { get; set; }
}

I use the following code to serialize the class:

string fileName = ...;
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
TextWriter textWriter = new StreamWriter(fileName);
try
{
    serializer.Serialize(textWriter, <instance of envelope>);
}
finally
{
    textWriter.Close();
}

When I assign an object of type Person to WrappedObject, I get the following XML:

<Envelope>
    <SomeValue>...</SomeValue>
    <WrappedObject xsi:type="Person">
        ....
    </WrappedObject>
</Envelope>

The problem is, I would like the tag for the wrapped object to be named after the actual class that I pass in. For example, if I assign an instance of Person to WrappedObject, I'd like the XML to look like the following:

<Envelope>
    <SomeValue>...</SomeValue>
    <Person>
        ....
    </Person>
</Envelope>

If I assign an instance of Animal, I'd like to get

<Envelope>
    <SomeValue>...</SomeValue>
    <Animal>
        ....
    </Animal>
</Envelope>

How would I achieve that?

EDIT

Actually I've simplified my example a little... The wrapped object is actually wrapped again:

public class Envelope
{
    public string SomeValue { get; set; }
    public Wrapper Wrap { get; set; }
}

[XmlInclude(typeof(Person))]
public class Wrapper
{
    public object WrappedObject { get; set; }
}

How would I handle this using the attributes override?

7
задан Aliostad 7 May 2011 в 22:28
поделиться