3

I'm trying to serialize a bool object using in the element text and I'm facing a really strange behavior. I'm getting an error with the next code:

[XmlRoot]
public class A
{
}

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

and serializing

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

The exceptions details are:

"There was an error reflecting type 'ConsoleApplication2.B"

and the inner exception says:

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

Changing the classes definition like this:

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 like this:

[XmlRoot]
public class A
{
}

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

It serializes correctly, but in the first case I'm losing the inheritance, in the second case the value is in another element instead of being in the text and in the last one I lose the type for a string.

Does anyone know what am I missing?

1 Answer 1

2

According to Microsoft this is not a bug, it is that way 'by design', but I can't find the documentation about that limitation. Anyway, I will just try any of the possible workarounds.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.