Serialise standard xml envelope containing variable contents



I want to create a serialisable class to represent an xml envelope that can contain arbitrary message content. Example xml (simplified) below:



<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<MessageA>
<Url></Url>
</MessageA>
</Envelope>

<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<MessageB>
<Value></Value>
</MessageB>
</Envelope>


My idea is to use a generic envelope class to handle this:



[Serializable]
[XmlRoot(ElementName="Envelope")]
public class Envelope<TContent> where TContent : new()
{
public Envelope()
{
Content = new TContent();
}
public TContent Content { get; set; }
}

[Serializable]
public class MessageA
{
public string Url { get; set; }
}

[Serializable]
public class MessageB
{
public string Value { get; set; }
}


These could be serialised so:



var envelope = new Envelope<MessageA>();
envelope.Content.Url = "http://www.contoso.com";
string xml = envelope.ToXml();


However, instead of the xml message that I want (per examples above), I get the following. How can I change the classes or the serialisation process to rename the Content element to the name of the Message itself?



<?xml version="1.0" encoding="utf-8"?>
<Envelope>
<Content>
<Url>http://ift.tt/1yyLoY7;
</Content>
</Envelope>

No comments:

Post a Comment