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?
Ryan Kohn
13.1k14 gold badges56 silver badges81 bronze badges
asked Sep 13, 2008 at 14:40
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.
dbc
105k20 gold badges229 silver badges341 bronze badges
answered Sep 13, 2008 at 14:53
LamarLamar
9,7794 gold badges30 silver badges18 bronze badges
15
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.
answered Sep 13, 2008 at 16:23
Jeremy McGeeJeremy McGee
24.9k10 gold badges63 silver badges95 bronze badges
3
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.
answered Sep 16, 2011 at 21:51
1
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
answered Feb 22, 2014 at 12:29
Stefan MichevStefan Michev
4,8053 gold badges35 silver badges30 bronze badges
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
answered Sep 13, 2008 at 17:31
Rob CooperRob Cooper
28.6k26 gold badges103 silver badges142 bronze badges
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.
answered Apr 26, 2010 at 18:34
LucaLuca
11.7k11 gold badges70 silver badges125 bronze badges
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>
.
dbc
105k20 gold badges229 silver badges341 bronze badges
answered Jan 12, 2012 at 12:59
jkokorianjkokorian
2,9057 gold badges32 silver badges47 bronze badges
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.
answered Jul 2, 2009 at 19:32
Charlie SaltsCharlie Salts
13.1k7 gold badges49 silver badges78 bronze badges
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.
answered Dec 17, 2010 at 14:15
LepardUKLepardUK
1,3301 gold badge11 silver badges17 bronze badges
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.
answered Sep 13, 2008 at 15:23
DarrenDarren
9612 gold badges9 silver badges17 bronze badges
Sometime, this type of error is because you dont have constructur of class without argument
answered Feb 20, 2021 at 8:50
Esperento57Esperento57
16.6k3 gold badges39 silver badges45 bronze badges
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.
Suraj Singh
4,0411 gold badge21 silver badges36 bronze badges
answered Dec 17, 2012 at 22:22
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; }
halfer
19.9k17 gold badges100 silver badges187 bronze badges
answered Dec 17, 2019 at 10:58
Iqra.Iqra.
6851 gold badge7 silver badges18 bronze badges
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.
answered Sep 13, 2008 at 14:55
Phil WrightPhil Wright
22.6k14 gold badges84 silver badges137 bronze badges
I have been using the NetDataSerialiser
class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
answered Sep 16, 2008 at 13:14
I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
answered May 26, 2017 at 1:19
1
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");
}
}
answered Dec 17, 2019 at 10:55
chxzychxzy
4894 silver badges13 bronze badges
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}
halfer
19.9k17 gold badges100 silver badges187 bronze badges
answered Feb 16, 2017 at 11:48
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?
Ryan Kohn
13.1k14 gold badges56 silver badges81 bronze badges
asked Sep 13, 2008 at 14:40
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.
dbc
105k20 gold badges229 silver badges341 bronze badges
answered Sep 13, 2008 at 14:53
LamarLamar
9,7794 gold badges30 silver badges18 bronze badges
15
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.
answered Sep 13, 2008 at 16:23
Jeremy McGeeJeremy McGee
24.9k10 gold badges63 silver badges95 bronze badges
3
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.
answered Sep 16, 2011 at 21:51
1
Most common reasons by me:
- the object being serialized has no parameterless constructor
- the object contains Dictionary
- the object has some public Interface members
answered Feb 22, 2014 at 12:29
Stefan MichevStefan Michev
4,8053 gold badges35 silver badges30 bronze badges
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
answered Sep 13, 2008 at 17:31
Rob CooperRob Cooper
28.6k26 gold badges103 silver badges142 bronze badges
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.
answered Apr 26, 2010 at 18:34
LucaLuca
11.7k11 gold badges70 silver badges125 bronze badges
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>
.
dbc
105k20 gold badges229 silver badges341 bronze badges
answered Jan 12, 2012 at 12:59
jkokorianjkokorian
2,9057 gold badges32 silver badges47 bronze badges
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.
answered Jul 2, 2009 at 19:32
Charlie SaltsCharlie Salts
13.1k7 gold badges49 silver badges78 bronze badges
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.
answered Dec 17, 2010 at 14:15
LepardUKLepardUK
1,3301 gold badge11 silver badges17 bronze badges
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.
answered Sep 13, 2008 at 15:23
DarrenDarren
9612 gold badges9 silver badges17 bronze badges
Sometime, this type of error is because you dont have constructur of class without argument
answered Feb 20, 2021 at 8:50
Esperento57Esperento57
16.6k3 gold badges39 silver badges45 bronze badges
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.
Suraj Singh
4,0411 gold badge21 silver badges36 bronze badges
answered Dec 17, 2012 at 22:22
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; }
halfer
19.9k17 gold badges100 silver badges187 bronze badges
answered Dec 17, 2019 at 10:58
Iqra.Iqra.
6851 gold badge7 silver badges18 bronze badges
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.
answered Sep 13, 2008 at 14:55
Phil WrightPhil Wright
22.6k14 gold badges84 silver badges137 bronze badges
I have been using the NetDataSerialiser
class to serialise
my domain classes. NetDataContractSerializer Class.
The domain classes are shared between client and server.
answered Sep 16, 2008 at 13:14
I had the same issue and in my case the object had a ReadOnlyCollection. A collection must implement Add method to be serializable.
answered May 26, 2017 at 1:19
1
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");
}
}
answered Dec 17, 2019 at 10:55
chxzychxzy
4894 silver badges13 bronze badges
[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
Or
[XmlIgnore]
string [] strFielsName {get;set;}
halfer
19.9k17 gold badges100 silver badges187 bronze badges
answered Feb 16, 2017 at 11:48
pincet 1625 / 1127 / 169 Регистрация: 23.07.2010 Сообщений: 6,661 |
||||
1 |
||||
Возникла ошибка при отражении типа20.11.2013, 13:51. Показов 7204. Ответов 5 Метки нет (Все метки)
где руки править?
0 |
17346 / 12757 / 3338 Регистрация: 17.09.2011 Сообщений: 21,036 |
|
20.11.2013, 14:54 |
2 |
Лезьте в свойство InnerException до тех пор, пока оно не станет null.
1 |
pincet 1625 / 1127 / 169 Регистрация: 23.07.2010 Сообщений: 6,661 |
||||||||
20.11.2013, 15:22 [ТС] |
3 |
|||||||
Хм, ошибка вот здесь
XMLSerialization.TW. XmlAttribute/XmlText не может использоваться для кодирования составных типов
убрал [XmlAttribute] «<TabPage xmlns=»> не ожидался.» 1.ЧЯДНТ?
0 |
kolorotur 17346 / 12757 / 3338 Регистрация: 17.09.2011 Сообщений: 21,036 |
||||||||||||
20.11.2013, 17:20 |
4 |
|||||||||||
«<TabPage xmlns=»> не ожидался.» У вас классы называются TW, TP и так далее, а элементы в разметке — TabPage, TreeView и т.д. Либо называйте классы так же, как элементы в разметке, либо элементы в разметке называйте так же, как классы, либо классы пометьте атрибутом XmlType:
Вернет null.
1 |
pincet 1625 / 1127 / 169 Регистрация: 23.07.2010 Сообщений: 6,661 |
||||
20.11.2013, 17:40 [ТС] |
5 |
|||
С этим уже разобрался. Проблема в другом
т.е нужно оборачивать в доп тэги Parent и Node.
0 |
sanmar1no 0 / 0 / 1 Регистрация: 13.01.2016 Сообщений: 8 |
||||
30.08.2023, 18:12 |
6 |
|||
С этим уже разобрался. Проблема в другом, если решил задачу помоги другу)
Примерно так?
0 |
[Serializable]
public class IPzag
{
public BitArray version = new BitArray(4);//номер версии 4 бита
public BitArray header_length = new BitArray(4);//Длина заголовка 4 бита
public BitArray toS = new BitArray(8);//тип сервиса 8 бит
public ushort total_lenght;//Общая длина 16 бит
public ushort identification;//Идентификатор пакета 16 бит
public BitArray flag = new BitArray(3);//Флаги 3 бита
public BitArray fragment_offset = new BitArray(13);//Смещение фрагмента 13 бит
public byte ttl;//Время жизни 8 бит Time To Live
public byte protocol;//Протокол верхнего уровня 8 бит
public ushort checksum;//Контрольная сумма 16 бит
public uint sourse_address;//айпишник источника 32 бита
public uint destination_adress;//айпишник назначения 32 бита
[DisplayName(«Номер версии»)]
[XmlAttribute()]
public BitArray Version
{
get { return version; }
set { for (int i = 0; i < 4; i++) version[i] = Convert.ToBoolean(value); }
}
[DisplayName(«Длина заголовка»)]
[XmlAttribute()]
public BitArray Header_Length
{
get { return header_length; }
set { for (int i = 0; i < 4; i++) header_length[i] = Convert.ToBoolean(value); }
}
[DisplayName(«Тип сервиса»)]
[XmlAttribute()]
public BitArray ToS
{
get { return toS; }
set { for (int i = 0; i < 4; i++) toS[i] = Convert.ToBoolean(value); }
}
[DisplayName(«Общая длина»)]
[XmlAttribute()]
public ushort Total_lenght
{
get { return total_lenght; }
set { total_lenght = value; }
}
[DisplayName(«Идентификатор пакета»)]
[XmlAttribute()]
public ushort Identification
{
get { return identification; }
set { identification = value; }
}
[DisplayName(«Время жизни»)]
[XmlAttribute()]
public byte TTL
{
get { return ttl; }
set { ttl = value; }
}
[DisplayName(«IP-Протокол верхнего уровня»)]
[XmlAttribute()]
public byte Protocol
{
get { return protocol; }
set { protocol = value; }
}
[DisplayName(«Контрольная сумма»)]
[XmlAttribute()]
public ushort Checksum
{
get { return checksum; }
set { checksum = value; }
}
[DisplayName(«IP-адрес источника»)]
[XmlAttribute()]
public uint Sourse_address
{
get { return sourse_address; }
set { sourse_address = value; }
}
[DisplayName(«IP-адрес назначения»)]
[XmlAttribute()]
public uint Destination_adress
{
get { return destination_adress; }
set { destination_adress = value; }
}
[DisplayName(«Флаги»)]
[XmlAttribute()]
public BitArray Flag
{
get { return flag; }
set { for (int i = 0; i < 4; i++) fragment_offset[i] = Convert.ToBoolean(value); }
}
[DisplayName(«Смещение фрагмента»)]
[XmlAttribute()]
public BitArray Fragment_offset
{
get { return fragment_offset; }
set { for (int i = 0; i < 4; i++) fragment_offset[i] = Convert.ToBoolean(value); }
}
public IPzag()
{
}
}
[Solved-3 Solutions] XmlSerializer — There was an error reflecting type
Error Description:
- Using C# .NET 2.0, we have a composite data class that does have the
[Serializable]
attribute on it. When we create anXMLSerializer
class and pass that into the constructor:
XmlSerializer serializer = new XmlSerializer(typeof(DataClass));
click below button to copy the code. By — C# tutorial — team
- We get this exemption saying:
There was an error reflecting type.
Solution 1:
- Look at the inner exception that you are getting. It will tell which field/property it is having trouble serializing.
- We can exclude fields/properties from xml serialization by decorating them with the
[XmlIgnore]
attribute.
Solution 2:
- Serialized classes must have default (i.e. parameter less) constructors. If we have no constructor at all, that’s fine; but if we have a constructor with a parameter, we’ll need to add the default one too.
Solution 3:
- All the objects in the serialization graph have to be serializable.
- Since
XMLSerializer
is a black box, 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