This is one i struggled with for ages so thought I'd document somewhere. (Apologies for asking and answering a question.)
(C# .net 2.0)
I had a class that was being serialized by XmlSerializer, I added a new public property however it wasn't being included in the output XML.
It's not mentioned in the docs anywhere I could find, but public properties must have a set as well as a get to be serialized! I guess this is because it assumes that if you're going to serialize then you'll want to deserialize from the same file, so only serializes properties that have both a set and a get.
As mentioned, most properties must have both a getter and setter; the main exception to this is lists - for example:
private readonly List<Foo> bar = new List<Foo>();
public List<Foo> Bar {get { return bar; } } // works fine
which will work fine; however, if XmlSerializer finds a setter - it demands that it is public; the following will not work:
public List<Foo> Bar {get; private set;} // FAIL
Other reasons it might not serialize:
it isn't public with get and set (or is readonly for a field)
it has a [DefaultValue] attribute, and is with that value
it has a public bool ShouldSerializeFoo() method that returned false
it has a public bool FooSpecified {get;set;} property or field that returned false
it is marked [XmlIgnore]
it is marked [Obsolete]
Any of these will cause it not to serialize
The point about getter+setter is made in the 3rd paragraph on the "Intro to Xml Serialization" page. It's actually in a call-out box. Can't miss it!
Intro-to-XML Serialization http://www.freeimagehosting.net/uploads/2f04fea2db.png
(having a little too much fun with Freeimagehosting.net)
Also properties that return null are not serialized!
if you don't want to implement proper Setters (because maybe you are neither wanting to deserialize or change an objects value) you can just use dummy setters like this set { }, so that the XMLSerializer works, but nothing happens if you use the Setter...
i.E.
public string ID { get { return _item.ID.ToString(); } set { } }
And if your class inherits a list and also has its own members, only the elements of the list get serialized. The data present in your class members is not captured.
Took some time figuring out this!
One more thing to add about serialization of collections:
The XmlSerializer ignores collections of interfaces!
And by that I mean ignore. While you will get an exception for a line like:
public IFoo Foo { get; set; }
you will not get an exception for:
public ICollection<IFoo> LotsOfFoos { get { return this.fooBackingField; } }
You can implement the IXmlSerializer and do the serialization manually, and benefit from serializing properties, and vice versa, deserializing them using constructors / private field assignment.
Related
We have some setup classes in our project, which are serialized / deserialized with XmlSerializer from some .config-Files. In some of those setup classes we have collections of sub-setups like this:
using System;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
namespace Datev.Framework.Shared.Actions.Setup
{
[Serializable]
[XmlSerializerAssembly]
[XmlRoot("setup")]
public class SetupXml
{
public SetupXml()
{
SubSetups = new Collection<SubSetupXml>();
}
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public Collection<SubSetupXml> SubSetups { get; private set; }
}
[Serializable]
public class SubSetupXml
{
[XmlElement("someValue")]
public string SomeValue { get; set; }
}
}
We are using the attribute [XmlSerializerAssembly] to have the best performance for reading and writing the setups.
And here is my problem: We are using Collection to avoid the CA-Warning "Don't use arrays". When we make the setter of SubSetups public, we get the CA-Warning CA2227 "Don't make the setter of a collection public". If we make the setter of the property SubSetups private (like in the code sample), we'll get an error in the generated serializer. The method "GenerateSerializer" (invoked in a tool of us) the code has a line like this:
if (o.SubSetups == null) o.SubSetups = new Collection<SubSetupXml>();
If we make the setter private, we'll get a CS0200 "Property SubSetups cannont be assigned" during building the serializer.
Does anyone know how to make a correct setup with a generated serializer without suppressing a CA-Warning?
It is hard to tell: a "correct" setup depends highly on the context.
Just a quick idea: what happens if you move the logic from "GenerateSerializer" to the property getter? Would it be acceptable?
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public Collection<SubSetupXml> SubSetups {
get {
// subSetups needs to be a backing (private) field... is this a problem?
if (this.subSetups == null) this.subSetups = new Collection<SubSetupXml>();
}
private set;
}
This way, in "GenerateSerializer" you just get the collection. If the collection has not already been created, it will be inside the getter, without needing to create it outside the class.
Just an idea, let me know if it is not applicable.
If the situation is as straightforward as it seems then You don't need to check whether (o.SubSetups == null) because You have the line SubSetups = new Collection<SubSetupXml>(); in the SetupXml() constructor (that is, of course, if o is of type SetupXml). If you get rid of that if statement from the GenerateSerializer method and make the setter private You should be fine - there's no way the SubSetups property can be null unless there are some other ways of messing around with it that You didn't mention...
You could have something like this:
public class SetupXml
{
public SetupXml()
{
SubSetups = new Collection<SubSetupXml>();
}
[XmlIgnore]
public Collection<SubSetupXml> SubSetups { get; private set; }
[EditorBrowsable(EditorBrowsableState.Never)]
[GeneratedCodeAttribute("Whatever", "1.0.0.0")]
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public SubSetupXml[] SerializationSubSetups
{
get
{
return SubSetups.ToArray();
}
get
{
SubSetups = new SubSetups();
if (value != null)
{
foreach(SubSetupXml ssx in value)
{
SubSetups.Add(ssx);
}
}
}
}
}
It's not perfect, but the EditorBrowsable attribute will prevent developers using this library (from another assembly) to see it displayed by intellisense/autocompletion tools. And the GeneratedCode attribute will prevent CA warning on it.
I assume that you have already consulted this article?
http://msdn.microsoft.com/en-us/library/ms182327.aspx
This strikes me as an important note in that article:
"Both binary and XML serialization support read-only properties that are collections. The System.Xml.Serialization.XmlSerializer class has specific requirements for types that implement ICollection and System.Collections.IEnumerable in order to be serializable."
Further to that you may be able to make more progress with the .Clear() and then .AddRange() approach, detailed there.
You can try to implement IXmlSerializable interface. It requires a bit more work but it gives you fine control on the serialization, and in your case access to the private class variables. In ReadXml method you just have to create and instance of your collection, iterate over each node in the source xml and parse the value
Changing the type of SubSetups to IEnumerable will get rid of the code analysis warning, but I can't tell if this is appropriate for you.
[XmlArray("subSetups")]
[XmlArrayItem("subSetup")]
public IEnumerable<SubSetupXml> SubSetups { get; set; }
Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
I am getting an exception saying:
There was an error reflecting type.
Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute.
XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:
'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.
Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.
What I needed to do was add an attribute to one of the classes (I added to the base class):
[XmlType("BaseNamespace.Class1")]
Note: If you have more layers of classes you need to add an attribute to them as well.
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
Also be aware that XmlSerializer cannot serialize abstract properties.. See my question here (which I have added the solution code to)..
XML Serialization and Inherited Types
All the objects in the serialization graph have to be serializable.
Since XMLSerializer is a blackbox, check these links if you want to debug further into the serialization process..
Changing where XmlSerializer Outputs Temporary Assemblies
HOW TO: Debug into a .NET XmlSerializer Generated Assembly
If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.
public class NetService : IXmlSerializable
{
#region Data
public string Identifier = String.Empty;
public string Name = String.Empty;
public IPAddress Address = IPAddress.None;
public int Port = 7777;
#endregion
#region IXmlSerializable Implementation
public XmlSchema GetSchema() { return (null); }
public void ReadXml(XmlReader reader)
{
// Attributes
Identifier = reader[XML_IDENTIFIER];
if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
}
public void WriteXml(XmlWriter writer)
{
// Attributes
writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
}
private const string XML_IDENTIFIER = "Id";
private const string XML_NETWORK_ADDR = "Address";
private const string XML_NETWORK_PORT = "Port";
#endregion
}
There is an interesting article, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.
The article say:
IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.
Because this, I suggest to implement you're own IXmlSerializable classes, in order to avoid too much complicated implementations.
...it could be straightforward to implements our custom XmlSerializer class using reflection.
I just got the same error and discovered that a property of type IEnumerable<SomeClass> was the problem. It appears that IEnumerable cannot be serialized directly.
Instead, one could use List<SomeClass>.
I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.
I found a work around here.
I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.
[System.Xml.Serialization.XmlElementAttribute(Order = XX)]
I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.
I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the SnippetCompiler:
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Inner
{
private string _AnotherStringProperty;
public string AnotherStringProperty
{
get { return _AnotherStringProperty; }
set { _AnotherStringProperty = value; }
}
}
public class DataClass
{
private string _StringProperty;
public string StringProperty
{
get { return _StringProperty; }
set{ _StringProperty = value; }
}
private Inner _InnerObject;
public Inner InnerObject
{
get { return _InnerObject; }
set { _InnerObject = value; }
}
}
public class MyClass
{
public static void Main()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
TextWriter writer = new StreamWriter(#"c:\tmp\dataClass.xml");
DataClass clazz = new DataClass();
Inner inner = new Inner();
inner.AnotherStringProperty = "Foo2";
clazz.InnerObject = inner;
clazz.StringProperty = "foo";
serializer.Serialize(writer, clazz);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
I would imagine that the XmlSerializer is using reflection over the public properties.
Sometime, this type of error is because you dont have constructur of class without argument
I had a situation where the Order was the same for two elements in a row
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]
.... some code ...
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]
When I changed the code to increment the order by one for each new Property in the class, the error went away.
I was getting the same error when I created a property having a datatype - Type. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was Type) in my case. The solution is as follows:
[XmlIgnore]
public Type Type { get; set; }
Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.
I have been using the NetDataSerialiser class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
I have a slightly different solution to all described here so far, so for any future civilisation here's mine!
I had declared a datatype of "time" as the original type was a TimeSpan and subsequently changed to a String:
[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]
however the actual type was a string
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
by removing the DateType property the Xml can be serialized
[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}
This is not a duplicate of this question. I have to serialize the Property which is "ReadOnly". I can't do anything on this class, because this is System.Web.Security.MembershipUser class, of course this is not sealed class.
[WebGet]
public string GetAllUsers()
{
List<MembershipUser> membershipList = new List<MembershipUser>();
MembershipUserCollection userCollection = Membership.GetAllUsers();
foreach (MembershipUser user in userCollection)
membershipList.Add(user);
string memberCollection = SerializeToString(membershipList, typeof(List<MembershipUser>));
List<MembershipUser> users = Deserialize(memberCollection, typeof(List<MembershipUser>)) as List<MembershipUser>;
return memberCollection;
}
Above code is what I used,
MembershipUserCollection userCollection = Membership.GetAllUsers();
GetAllUsers method returns MembershipUserCollection, but this does not have default accessor. So while serializing I get exception. That is the reason I went with List<MembershipUser>. Here too I face trouble. This is eating my day, what could solve this?.
Edit:
I'm using XmlSerializer.
Serializing will only serialize public fields as well as public properties that you can both get and set. The reason for the latter is that if you cannot set it, then when you go to deserialize it, how do you set the property?
Since the class isn't sealed, you could inherit from it, define a setter, but have it do nothing, i.e.
public string Name
{
get {return _name;}
set { }
}
The thing to look out for is when you deserialize to that class, the data will be lost.
HTH,
Brian
I would suggest creating a wrapper over MembershipUserCollection for your serialization/deserialization purpose.
Also, Are you sure that above code is throwing exception because fields have private members? It may be because of missing Serializableattribute or default constructor!!!
I swear I have seen an example of this but have been googling for a bit and can not find it.
I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class).
Thanks
No, there's no way of doing this. For instance, if you return a List<string> (and it's not immutable) then callers will be able to add entries.
The normal way round this is to return an immutable wrapper, e.g. ReadOnlyCollection<T>.
For other mutable types, you may need to clone the value before returning it.
Note that just returning an immutable interface view (e.g. returning IEnumerable<T> instead of List<T>) won't stop a caller from casting back to the mutable type and mutating.
EDIT: Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)
Return a reference to a stripped-down interface:
interface IFoo
string Bar { get; }
class ClassWithGet
public IFoo GetFoo(...);
If the object isn't too complicated/extensive then write an wrapper around it.
for example:
class A {
public string strField = 'string';
public int intField = 10;
}
class AWrapper {
private A _aObj;
public AWrapper(A aobj) {
_aObj = A;
}
public string strField {
get {
return _aObj.strField;
}
}
public int intField {
get {
return _aObj.intField;
}
}
}
So now all you do is give your client code an instance of the AWrapper class so that they may only use what you allow them to see.
this may get a bit complicated and may not scale well if your base class is not set in stone, but for most simple situation it may just do the trick. I think this is called a facade pattern(but don't quote me on that =) )
This isn't possible. Get and set accessors to reference types get and set the reference to the object. You can prevent changes to the reference by using a private (or internal) setter, but you cannot prevent changes to the object itself if it's exposed by a getter.
Your question reads like you're looking for:
public PropertyName { get; private set; }
But then, given the answers so far I'm not sure I'm interpreting your question correctly. Besides, who am I to question Jon Skeet? :)
i agree with ReadOnlyCollection
See my simple code:
private List<Device> _devices;
public readonly System.Collections.ObjectModel.ReadOnlyCollection<Device> Devices
{
get
{
return (_devices.AsReadOnly());
}
}
ReadOnlyCollection dosen't has Add method so user cant add properties to it.BUT ther is no warranty that if user can modify objects by calling their methods....
I have faced this problem in a certain way.
I have a CategoryViewModel class, which have a property Category that I want private read-only :
public CategoryViewModel
{
private Category { get; }
}
In fact, I want it to be exported as read-only to other class. However I can't do such thing.
In my case (maybe it will help some other guys), I want to add it to a repository. The only way that I've found is to have a function with the repository as param 1, and an Action as param 2 :
public void ApplyAction(ICategoryRepository repo, Action<ICategoryRepository, Category> action)
{
action(repo, Category);
}
Like that, from elsewhere, I can do such thing :
categoryViewModel.ApplyAction(_repository, (r, c) => r.MarkForInsertOrUpdate(c));
This can help other to expose there property only for certains cases and can manage them.
Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it. I am creating an XMLSerializer class and passing that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
I am getting an exception saying:
There was an error reflecting type.
Inside the data class there is another composite object. Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the [XmlIgnore] attribute.
XmlSerializer does not use the [Serializable] attribute, so I doubt that is the problem.
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
I had a similar problem, and it turned out that the serializer could not distinguish between 2 classes I had with the same name (one was a subclass of the other). The inner exception looked like this:
'Types BaseNamespace.Class1' and 'BaseNamespace.SubNamespace.Class1' both use the XML type name, 'Class1', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.
Where BaseNamespace.SubNamespace.Class1 is a subclass of BaseNamespace.Class1.
What I needed to do was add an attribute to one of the classes (I added to the base class):
[XmlType("BaseNamespace.Class1")]
Note: If you have more layers of classes you need to add an attribute to them as well.
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
Also be aware that XmlSerializer cannot serialize abstract properties.. See my question here (which I have added the solution code to)..
XML Serialization and Inherited Types
All the objects in the serialization graph have to be serializable.
Since XMLSerializer is a blackbox, check these links if you want to debug further into the serialization process..
Changing where XmlSerializer Outputs Temporary Assemblies
HOW TO: Debug into a .NET XmlSerializer Generated Assembly
If you need to handle specific attributes (i.e. Dictionary, or any class), you can implement the IXmlSerialiable interface, which will allow you more freedom at the cost of more verbose coding.
public class NetService : IXmlSerializable
{
#region Data
public string Identifier = String.Empty;
public string Name = String.Empty;
public IPAddress Address = IPAddress.None;
public int Port = 7777;
#endregion
#region IXmlSerializable Implementation
public XmlSchema GetSchema() { return (null); }
public void ReadXml(XmlReader reader)
{
// Attributes
Identifier = reader[XML_IDENTIFIER];
if (Int32.TryParse(reader[XML_NETWORK_PORT], out Port) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_PORT);
if (IPAddress.TryParse(reader[XML_NETWORK_ADDR], out Address) == false)
throw new XmlException("unable to parse the element " + typeof(NetService).Name + " (badly formatted parameter " + XML_NETWORK_ADDR);
}
public void WriteXml(XmlWriter writer)
{
// Attributes
writer.WriteAttributeString(XML_IDENTIFIER, Identifier);
writer.WriteAttributeString(XML_NETWORK_ADDR, Address.ToString());
writer.WriteAttributeString(XML_NETWORK_PORT, Port.ToString());
}
private const string XML_IDENTIFIER = "Id";
private const string XML_NETWORK_ADDR = "Address";
private const string XML_NETWORK_PORT = "Port";
#endregion
}
There is an interesting article, which show an elegant way to implements a sophisticated way to "extend" the XmlSerializer.
The article say:
IXmlSerializable is covered in the official documentation, but the documentation states it's not intended for public use and provides no information beyond that. This indicates that the development team wanted to reserve the right to modify, disable, or even completely remove this extensibility hook down the road. However, as long as you're willing to accept this uncertainty and deal with possible changes in the future, there's no reason whatsoever you can't take advantage of it.
Because this, I suggest to implement you're own IXmlSerializable classes, in order to avoid too much complicated implementations.
...it could be straightforward to implements our custom XmlSerializer class using reflection.
I just got the same error and discovered that a property of type IEnumerable<SomeClass> was the problem. It appears that IEnumerable cannot be serialized directly.
Instead, one could use List<SomeClass>.
I've discovered that the Dictionary class in .Net 2.0 is not serializable using XML, but serializes well when binary serialization is used.
I found a work around here.
I recently got this in a web reference partial class when adding a new property. The auto generated class was adding the following attributes.
[System.Xml.Serialization.XmlElementAttribute(Order = XX)]
I needed to add a similar attribute with an order one higher than the last in the auto generated sequence and this fixed it for me.
I too thought that the Serializable attribute had to be on the object but unless I'm being a complete noob (I am in the middle of a late night coding session) the following works from the SnippetCompiler:
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
public class Inner
{
private string _AnotherStringProperty;
public string AnotherStringProperty
{
get { return _AnotherStringProperty; }
set { _AnotherStringProperty = value; }
}
}
public class DataClass
{
private string _StringProperty;
public string StringProperty
{
get { return _StringProperty; }
set{ _StringProperty = value; }
}
private Inner _InnerObject;
public Inner InnerObject
{
get { return _InnerObject; }
set { _InnerObject = value; }
}
}
public class MyClass
{
public static void Main()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
TextWriter writer = new StreamWriter(#"c:\tmp\dataClass.xml");
DataClass clazz = new DataClass();
Inner inner = new Inner();
inner.AnotherStringProperty = "Foo2";
clazz.InnerObject = inner;
clazz.StringProperty = "foo";
serializer.Serialize(writer, clazz);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
I would imagine that the XmlSerializer is using reflection over the public properties.
Sometime, this type of error is because you dont have constructur of class without argument
I had a situation where the Order was the same for two elements in a row
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "SeriousInjuryFlag")]
.... some code ...
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true, Order = 0, ElementName = "AccidentFlag")]
When I changed the code to increment the order by one for each new Property in the class, the error went away.
I was getting the same error when I created a property having a datatype - Type. On this, I was getting an error - There was an error reflecting type. I kept checking the 'InnerException' of every exception from the debug dock and got the specific field name (which was Type) in my case. The solution is as follows:
[XmlIgnore]
public Type Type { get; set; }
Also note that you cannot serialize user interface controls and that any object you want to pass onto the clipboard must be serializable otherwise it cannot be passed across to other processes.
I have been using the NetDataSerialiser class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
I have a slightly different solution to all described here so far, so for any future civilisation here's mine!
I had declared a datatype of "time" as the original type was a TimeSpan and subsequently changed to a String:
[System.Xml.Serialization.XmlElementAttribute(DataType="time", Order=3)]
however the actual type was a string
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
by removing the DateType property the Xml can be serialized
[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public string TimeProperty {
get {
return this.timePropertyField;
}
set {
this.timePropertyField = value;
this.RaisePropertyChanged("TimeProperty");
}
}
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}