Возникла ошибка при отражении типа xmlserializer

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's user avatar

Ryan Kohn

13.1k14 gold badges56 silver badges81 bronze badges

asked Sep 13, 2008 at 14:40

leora's user avatar

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's user avatar

dbc

105k20 gold badges229 silver badges341 bronze badges

answered Sep 13, 2008 at 14:53

Lamar's user avatar

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 McGee's user avatar

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

Dennis Calla's user avatar

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 Michev's user avatar

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

Community's user avatar

answered Sep 13, 2008 at 17:31

Rob Cooper's user avatar

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.

Peter Mortensen's user avatar

answered Apr 26, 2010 at 18:34

Luca's user avatar

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's user avatar

dbc

105k20 gold badges229 silver badges341 bronze badges

answered Jan 12, 2012 at 12:59

jkokorian's user avatar

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 Salts's user avatar

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

LepardUK's user avatar

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

Darren's user avatar

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

Esperento57's user avatar

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's user avatar

Suraj Singh

4,0411 gold badge21 silver badges36 bronze badges

answered Dec 17, 2012 at 22:22

Jeremy Brown's user avatar

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's user avatar

halfer

19.9k17 gold badges100 silver badges187 bronze badges

answered Dec 17, 2019 at 10:58

Iqra.'s user avatar

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 Wright's user avatar

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.

Peter Mortensen's user avatar

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

Curious Dev's user avatar

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

chxzy's user avatar

chxzychxzy

4894 silver badges13 bronze badges

[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

Or

[XmlIgnore]
string [] strFielsName {get;set;}

halfer's user avatar

halfer

19.9k17 gold badges100 silver badges187 bronze badges

answered Feb 16, 2017 at 11:48

Kiran.Bakwad's user avatar

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's user avatar

Ryan Kohn

13.1k14 gold badges56 silver badges81 bronze badges

asked Sep 13, 2008 at 14:40

leora's user avatar

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's user avatar

dbc

105k20 gold badges229 silver badges341 bronze badges

answered Sep 13, 2008 at 14:53

Lamar's user avatar

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 McGee's user avatar

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

Dennis Calla's user avatar

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 Michev's user avatar

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

Community's user avatar

answered Sep 13, 2008 at 17:31

Rob Cooper's user avatar

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.

Peter Mortensen's user avatar

answered Apr 26, 2010 at 18:34

Luca's user avatar

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's user avatar

dbc

105k20 gold badges229 silver badges341 bronze badges

answered Jan 12, 2012 at 12:59

jkokorian's user avatar

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 Salts's user avatar

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

LepardUK's user avatar

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

Darren's user avatar

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

Esperento57's user avatar

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's user avatar

Suraj Singh

4,0411 gold badge21 silver badges36 bronze badges

answered Dec 17, 2012 at 22:22

Jeremy Brown's user avatar

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's user avatar

halfer

19.9k17 gold badges100 silver badges187 bronze badges

answered Dec 17, 2019 at 10:58

Iqra.'s user avatar

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 Wright's user avatar

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.

Peter Mortensen's user avatar

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

Curious Dev's user avatar

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

chxzy's user avatar

chxzychxzy

4894 silver badges13 bronze badges

[System.Xml.Serialization.XmlElementAttribute("strFieldName", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

Or

[XmlIgnore]
string [] strFielsName {get;set;}

halfer's user avatar

halfer

19.9k17 gold badges100 silver badges187 bronze badges

answered Feb 16, 2017 at 11:48

Kiran.Bakwad's user avatar

pincet

1625 / 1127 / 169

Регистрация: 23.07.2010

Сообщений: 6,661

1

Возникла ошибка при отражении типа

20.11.2013, 13:51. Показов 7204. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
   public class TW
    {   
        [XmlAttribute]
        public string Name;
        [XmlArrayAttribute]
        public P[] Parent;
        public void ShowMe()
        {
            Console.WriteLine("{0}", Name);
            foreach (P p in Parent)
                p.ShowMe();
        }
    }
    public class P
    {
        [XmlAttribute]
        public string Name;
        [XmlAttribute]
        public string Text;
        [XmlAttribute]
        public string Type;
        [XmlAttribute]
        public string Path;
        [XmlArrayAttribute]
        public C[] Node;
        public void ShowMe()
        {
            Console.WriteLine("{0} {1} {2} {3}", Name, Text, Type, Path);
            foreach (C c in Node)
                c.ShowMe();
            
        }
    }
    public class C
    {
        [XmlAttribute]
        public string Name;
        [XmlAttribute]
        public string Text;
        public void ShowMe()
        {
            Console.WriteLine("{0} {1}",Name,Text);
        }
    }
    [Serializable]
    public class TP
    {
        [XmlAttribute]
        public string Name;
        [XmlAttribute]
        public string Descr;
        [XmlAttribute]
        public TW TreeView;
        public void ShowMe()
        {
            Console.WriteLine("{0} {1}", Name, Descr);
            TreeView.ShowMe();
        }
    }
    public class GUI
    {
        public GUI(XElement xe)
        {
            TP tp = new TP();
            XmlSerializer serializer = new XmlSerializer(typeof(TP));
            TextReader tr=new StringReader(xe.ToString());
            tp=(TP)serializer.Deserialize(tr);
            tp.ShowMe();
        }
 
    }
    class Program
    {
        static void Main(string[] args)
        {
            GUI g=new GUI(XDocument.Load("1.xml").Element("TabPage"));
        }
    }

где руки править?



0



Эксперт .NET

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

Хм, ошибка вот здесь

C#
1
2
 [XmlAttribute]
 public TW TreeView;

XMLSerialization.TW. XmlAttribute/XmlText не может использоваться для кодирования составных типов
тепрь есть понимние, что [XmlAttribute] не умеет сериализовать составные типы
Мечталось сериализовать вот такой xml

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<root>
<TabPage Name="Bookin" Descr="Справочники">
  <TreeView Name="Books">
    <Parent Name="Supp" Text="Поставка" Type="Book" Path="">
      <Node Name="" Text="Поставщики" />
      <Node Name="" Text="Контрагенты" />
    </Parent>
    <Parent Name="Materials" Text="Материалы" Type="Book" Path="">
      <Node Name="" Text="Сырье" />
      <Node Name="" Text="Полуфабрикаты" />
    </Parent>
    <Parent Name="FP" Text="Готовая продукция" Type="Book" Path="">
      <Node Name="" Text="Основной" />
      <Node Name="" Text="Основные материалы" />
      <Node Name="" Text="Штрих-коды" />
    </Parent>
    <Parent Name="Others" Text="Прочее" Type="Book" Path="" />
  </TreeView>
</TabPage>
</root>

убрал [XmlAttribute]
получил

«<TabPage xmlns=»> не ожидался.»

1.ЧЯДНТ?



0



kolorotur

Эксперт .NET

17346 / 12757 / 3338

Регистрация: 17.09.2011

Сообщений: 21,036

20.11.2013, 17:20

4

Цитата
Сообщение от pincet
Посмотреть сообщение

«<TabPage xmlns=»> не ожидался.»
1.ЧЯДНТ?

У вас классы называются TW, TP и так далее, а элементы в разметке — TabPage, TreeView и т.д.

Либо называйте классы так же, как элементы в разметке, либо элементы в разметке называйте так же, как классы, либо классы пометьте атрибутом XmlType:

C#
1
2
[XmlType("TabPage")]
public class TP

Цитата
Сообщение от pincet
Посмотреть сообщение

C#
1
XDocument.Load("1.xml").Element("TabPage")

Вернет null.

C#
1
XDocument.Load("1.xml").Root.Element("TabPage")



1



pincet

1625 / 1127 / 169

Регистрация: 23.07.2010

Сообщений: 6,661

20.11.2013, 17:40

 [ТС]

5

С этим уже разобрался. Проблема в другом
XML в предыдущем посте не совсем подготовлен для десериализации.
Рабочий вот такой

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<root>
<TabPage Name="Bookin" Descr="Справочники">
  <TreeView Name="Books">
    <Parents>
      <Parent Name="Supp" Text="Поставка" Type="Book" Path="">
        <Nodes>
          <Node Name="" Text="Поставщики" />
          <Node Name="" Text="Контрагенты" />
        </Nodes>
      </Parent>
    <Parent Name="Materials" Text="Материалы" Type="Book" Path="">
      <Nodes>
      <Node Name="" Text="Сырье" />
      <Node Name="" Text="Полуфабрикаты" />
      </Nodes>
    </Parent>
    <Parent Name="FP" Text="Готовая продукция" Type="Book" Path="">
      <Nodes>
      <Node Name="" Text="Основной" />
      <Node Name="" Text="Основные материалы" />
      <Node Name="" Text="Штрих-коды" />
      </Nodes>
    </Parent>
   </Parents>
  </TreeView>
</TabPage>
</root>

т.е нужно оборачивать в доп тэги Parent и Node.
Можно ли как-то выкрутиться и десериализовать первую версию? (много софта переписывать надо)



0



sanmar1no

0 / 0 / 1

Регистрация: 13.01.2016

Сообщений: 8

30.08.2023, 18:12

6

Цитата
Сообщение от pincet
Посмотреть сообщение

С этим уже разобрался.

Проблема в другом, если решил задачу помоги другу)

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System.Xml;
using System.Xml.Serialization;
 
namespace Test
{
 
    public class root
    {
        [XmlElement("TabPage")]
        public TabPage Page { get; set; }
    }
 
    public class TabPage
    {
        [XmlAttribute("Name")]
        public string Name { get; set; }
 
        [XmlAttribute("Descr")]
        public string Descr { get; set; }
        
        [XmlElement("TreeView")]
        public TreeView Tree { get; set; }
    }
 
    public class TreeView
    {
        [XmlAttribute("Name")]
        public string Name { get; set; }
        [XmlElement("Parent")]
        public Parent[] Parent { get; set; }
    }
 
    public class Parent
    {
        [XmlAttribute("Name")]
        public string Name { get; set; }
        [XmlAttribute("Text")]
        public string Text { get; set; }
        [XmlAttribute("Type")]
        public string Type { get; set; }
        [XmlAttribute("Path")]
        public string Path { get; set; }
 
        [XmlElement("Node")]
        public Node[] Items { get; set; }
    }
 
    public class Node
    {
        [XmlAttribute("Name")]
        public string Name { get; set; }
        [XmlAttribute("Text")]
        public string Text { get; set; }
    }
}

Примерно так?



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 an XMLSerializer 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


Понравилась статья? Поделить с друзьями:
  • Возникла ошибка при подготовке к отправке airdrop
  • Возникла ошибка при отправке отчета на сервер фсрар
  • Возникла ошибка при отправке электронной почты modx
  • Возникла ошибка при отправке реестра ошибка сервера фсс
  • Возникла ошибка при отправке кода днс