Route class:
[Serializable] [XmlRoot("Main")] public class MainClass { public MainClass() { Parents = new List<MyParent>(); } [XmlElement("Parent")] public List<MyParent> Parents { get; set; } } There is a parent class:
[Serializable] [XmlRoot("Parent")] public class MyParent { public enum myEnum : int { One, Two, Three }; [XmlAttribute("Id")] public string Id { get; set; } [XmlAttribute("Name")] public string Name { get; set; } } There is a class extending it:
[Serializable] [XmlRoot("Parent")] public class MyChild : MyParent { public MyChild() { Child = new List<InnerParameter>(); } [XmlElement("Child")] public List<InnerParameter> Child { get; set; } } This class reveals that inside the Child tag :
[Serializable] [XmlRoot("Child")] public class InnerParameter { public InnerParameter() { } [XmlText] public string Value { get; set; } } Then, I try to serialize:
MainClass newMainXml = new MainClass(); newMainXml.Parents = new List<MyParent>(); MyChild ch = new MyChild (); ch.Id = "123"; ch.Name = "Stefani"; InnerParameter parameter = new InnerParameter(); parameter.Value = "MyText"; ch.Child.Add(parameter); newMainXml.Parents.Add(ch); XmlSerialization.TrySerializeObjectToXmlString(newMainXml, out result); I want the following XML on output:
<Main> <Parent Id="123" Name="Stefani"> <Child>MyText</Child> </Parent> </Main> I get a serialization error:
Generating XML document. The type MyChild was not expected. Use the XmlInclude or SoapInclude attribute to specify types.
Tell me please, what am I doing wrong in the formation of xml? Why is serialization not working? ( There is a great suspicion that the matter here is in the inheritance and dependence of classes among themselves. Probably, I must say that MyChild is not the only class that extends MyParent ... )
PS: it looks like the situation is almost like mine: XML serialization of an object with a field of type Object C #
XmlSerialization.TrySerializeObjectToXmlStringdoes not look like a standard method. Show its implementation. - Pavel MayorovXmlInclude. - andreycha