I have a class which I want to serialize to xml. I want to move one of the properties down a level in the generated xml (an element within an element) without changing the structure of the class. Is it possible to do this using XmlSerializer?
An example:
Generated xml:
<Person>
<firstname xmlns=\"http://myschema.com\">John</firstname>
<postcode xmlns=\"http://myschema.com\">N1 0XE</postcode>
</Person>
Desired xml:
<Person>
<firstname xmlns=\"http://myschema.com\">John</firstname>
<address>
<postcode xmlns=\"http://myschema.com\">N1 0XE</postcode>
</address>
</Person>
The code:
[Serializable]
[XmlType(Namespace = "http://myschema.com")]
public class Person
{
[XmlElement("firstname")]
public string FirstName { get; set; }
[XmlElement("postcode")]
public string Postcode { get; set; }
}
Serializer:
var xmlSerializer = new XmlSerializer(typeof(Person));
var stringWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(stringWriter);
xmlSerializer.Serialize(xmlWriter, person);
The only way I know to change the generated standard output xml is to implement IXmlSerializable. So you do not have to change the common structure but you do have to provide the implementation for some methods.
@XmlSubElement – there are only a bunch of attributes available for xmlSerialization. Unfortunatelly there is no subElement or anything comparable.