开发者

Using XMLTextAttribute when inheriting a class

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 Xm开发者_运维技巧lSerializer(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜