I need to export a collection of items in camel casing, for this I use a wrapper.
The class itself:
[XmlRoot("example")]
public class Example
{
[XmlElement("exampleText")]
public string ExampleText { get; set; }
}
This serializes fine:
<example>
<exampleText>Some text</exampleText>
</example>
The wrapper:
[XmlRoot("examples")]
public class ExampleWrapper : ICollection<Example>
{
[XmlElement("example")]
public List<Example> innerList;
//Implementation of ICollection using innerList
}
This however capitalizes the wrapped Example
s for some reason, I tried to override it with XmlElement
but this doesn't seem to have the desired effect:
<examples>
<Example>
<exampleText>Some text</exampleText>
</Example>
<Example>
<exampleText>Another text</exampleText>
</Example>
</examples>
Who can tell me what I am doing wrong or if there is an easier way?
Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application.
The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.
The XmlTypeAttribute belongs to a family of attributes that controls how the XmlSerializer serializes or deserializes an object. For a complete list of similar attributes, see Attributes That Control XML Serialization. You can apply the XmlTypeAttribute to a class, structure, enumeration, or interface declaration.
XML serialization can take more than one form, from simple to complex. For example, you can serialize a class that simply consists of public fields and properties, as shown in Introducing XML Serialization.
The problem is that XmlSerializer
has built-in handling for collection types, meaning it it will ignore all your properties and fields (including innerList
) if your type happens to implement ICollection
and will just serialize it according to its own rules. However, you can customize the name of the element it uses for the collection items with the XmlType
attribute (as opposed to the XmlRoot
that you had used in your example):
[XmlType("example")]
public class Example
{
[XmlElement("exampleText")]
public string ExampleText { get; set; }
}
That will have the desired serialization.
See http://msdn.microsoft.com/en-us/library/ms950721.aspx, specifically the answer to the question "Why aren't all properties of collection classes serialized?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With