Using XMLTextAttribute in Class Inheritance

I am trying to serialize a bool object using element text, and I come across really weird behavior. I get an error with the following code:

[XmlRoot]
public class A
{
}

public class B : A 
{
    [XmlText]
    public bool value = false;
}

and serialization

using (StreamWriter sw = new StreamWriter("test.xml"))
{
    B b = new B();
    XmlSerializer serializer = new XmlSerializer(typeof(B));
    serializer.Serialize(sw, b);
}

Exception Details:

"An error occurred reflecting the type" ConsoleApplication2.B "

and internal exception says:

"Cannot serialize an object of type ConsoleApplication2.B. Consider changing the type of the XmlText element 'ConsoleApplication2.B.value' from System.Boolean to a string or string array.

Change the definition of classes as follows:

public class B
{
    [XmlText]
    public bool value = false;
}

or like this:

[XmlRoot]
public class A
{
}

public class B : A
{
    public bool value = false;
}

or even so:

[XmlRoot]
public class A
{
}

public class B : A
{
    [XmlText]
    public string value = "false";
}

It serializes correctly, but in the first case I lose inheritance, in the second case the value is in another element, not in the text, and in the latter I am losing the type for the string.

- , ?

+3
1

Microsoft, , " " , . , .

+2

Source: https://habr.com/ru/post/1792188/


All Articles