I have the problem when sequentially serialize-deserialize-serialize a TestClass:
[Serializable]
public class TestClass
{
public TestClass() { }
public Foo Foo { get; set; }
}
[XmlInclude(typeof(Bar))]
[Serializable]
public abstract class Foo
{
[XmlAnyAttribute]
public List<XmlAttribute> AnyAttr;
}
[Serializable]
public class Bar : Foo
{
}
void Test()
{
var test = new TestClass { Foo = new Bar() };
Console.WriteLine(test.Foo.AnyAttr == null);//true
var firstXml = Helper.SerializeToXml(test);
Console.WriteLine(Regex.Matches(firstXml, "xsi:type=").Count);//1
var deserialiezedObject = Helper.DeserializeFromXml<TestClass>(firstXml);
Console.WriteLine(deserialiezedObject.Foo.AnyAttr.Count);//1
Console.WriteLine(deserialiezedObject.Foo.AnyAttr[0].Name);//xsi:type
var secondXml = Helper.SerializeToXml(deserialiezedObject);
Console.WriteLine(Regex.Matches(secondXml, "xsi:type=").Count);//2
//var secondDeserialiezedObject = Helper.DeserializeFromXml<TestClass>(secondXml); //InvalidOperationException
}
As you can see the deserialization fills the AnyAttr array( by one element – “xsi:type”).
The strange thing happens after we serialize the deserialiezedObject. It produces the “xsi:type” twice in Foo tag.
Is this a XmlSerializer bug or I should manage (delete “xsi:type” from the AnyAttr after deserialization, for instance) the AnyAttr myself some way?
I have a bunch of auto generated classes which contain the AnyAttr field.
Could you suggest how to serialize objects like this without “xsi:type” duplication?
Didn’t find better solution than just deleting “xsi:type” from the AnyAttr (through reflection) after every deserialization