I’m after the following XML serialization output:
<?xml version="1.0"?>
<Message>
<Version>1.0</Version>
<Body>
<ExampleObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EmampleOne>Hello!</EmampleOne>
</ExampleObject>
</Body>
</Message>
I have the following classes:
[Serializable]
public class Message<T>
{
public string Version { get; set; }
public T Body { get; set; }
}
[Serializable]
public class ExampleObject
{
public string EmampleOne { get; set; }
}
If I serialize them separately I get:
<?xml version="1.0"?>
<Message>
<Version>1.0</Version>
<Body>
<EmampleOne>Hello!</EmampleOne>
</Body>
</Message>
And:
<?xml version="1.0"?>
<ExampleObject>
<EmampleOne>Hello!</EmampleOne>
</ExampleObject>
So as shown above I’m wanting the inner body to contain the class name <ExampleObject>.
I use generics as I need to have different Message Body’s, I serialize with the code:
var obj = new Message<ExampleObject>
{
Version = "1.0",
Body = example
};
var serializer2 = new XmlSerializer(typeof (Message<ExampleObject>));
As @Marc Gravell suggested in his comment, you can use XmlAttributeOverrides: