Is there a way to cause XmlSerializer to serialize primitive class members (e.g. string properties) as XML attributes, not as XML elements, without having to write [XmlAttribute] in front of each property declaration?
I.e. is there a global switch that tells XmlSerializer to serialize all primitive class members as XML attributes?
Assume that we have the following class:
public class Person
{
public string FirstName
{
...
}
public string LastName
{
...
}
}
Then XmlSerializer generates this code by default:
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
</Person>
What I want, however, is this code:
<Person FirstName="John" LastName="Doe"/>
Again: I want to do that without [XmlAttribute] (or without XmlAttributeOverrides, which would be even more work).
One possible solution would be to use a generic postprocessing step that applies an XSLT transform to convert elements to attributes. But I wonder whether there is a simpler solution.
One way to achieve this is to implement the serialization logic in a base class that implements the IXmlSerializable interface. The classes that are to be serialized to XML, would then have to derive from this base class in order to get the functionality.
Here’s an example
Here we are using Reflection to get a list of properties from the current object, whose type is a primitive or a String. These properties are then written to the XML output as attributes using the provided XmlWriter object.
The classes to be serialized would simply have to inherit from
XmlSerializableEntityto automatically get this behavior: