XML serialization of objects with envelope in 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 WrappedO开发者_StackOverflow中文版bject
, 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?
You need to use attribute override. I am using it heavily as I do a lot of custom serialisation.
This is a rough untested snippet but should point you in the right direction:
XmlAttributes attributes = new XmlAttributes();
XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();
attributes.XmlElements.Add(new XmlElementAttribute("Person", t));
xmlAttributeOverrides.Add(typeof(Person), "WrappedObject", attributes);
XmlSerializer myserialiser = new XmlSerializer(typeof(Envelope), xmlAttributeOverrides);
精彩评论