Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a custom IXmlSerializable as an XmlAttribute?

Tags:

c#

xml

I implement IXmlSerializable for the type below which encodes a RGB color value as a single string:

public class SerializableColor : IXmlSerializable
{
    public int R { get; set; }
    public int G { get; set; }
    public int B { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        var data = reader.ReadString();
        reader.ReadEndElement();
        var split = data.Split(' ');
        R = int.Parse(split[0]);
        G = int.Parse(split[1]);
        B = int.Parse(split[2]);
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteString(R + " " + G + " " + B);
    }
}

Since it's a single string, I wanted to store it as an attribute to save space. But as soon as I add the [XmlAttribute] to my property, I get the following exception:

{"Cannot serialize member 'Color' of type SerializableColor. XmlAttribute/XmlText cannot be used to encode types implementing IXmlSerializable."}

Is there a way to make it work as an attribute too?

like image 775
David Gouveia Avatar asked Jul 24 '12 16:07

David Gouveia


1 Answers

Sadly (& strangely) it is not possible according to this link http://connect.microsoft.com/VisualStudio/feedback/details/277641/xmlattribute-xmltext-cannot-be-used-to-encode-types-implementing-ixmlserializable

To work-around the problem, I am currently using the XmlIgnore attribute to hide the complex property and expose it as a string via another property

public class MyDto
{
    [XmlAttribute(AttributeName = "complex-attribute")]
    public string MyComplexPropertyAsString
    {
        get { return MyComplexMember.ToString(); }
        set { MyComplexMember.LoadFromString(value); }
    }
    [XmlIgnore]
    public MyComplexMember At { get; set; }
}
like image 121
ggrundy Avatar answered Oct 23 '22 06:10

ggrundy