简体   繁体   中英

Serialize Class as attribute

I have a Point class which I want to serialize as attribute. Here is the example of what I really want:

public class PointXY
{
    [XmlIgnore]
    public Double X { get; set; }

    [XmlIgnore]
    public Double Y { get; set; }

    public override string ToString()
    {
        return Points;
    }
}

public class TestClass
{
    [XmlAttribute]
    public PointXY Points { get; set; }
}

The Test Class should be serialized to:

<TestClass Points="0.1 0.2">

</TestClass>

I know this can be achieved if TestClass is implemented using IXmlSerializable interface. But what I want PointsXY should emmit itself as attribute instead of element. Is it possible? If yes how? This should get deserialized as well.

I don't know of a way to serialize an entire class as an attribute.

You're going to either have to implement IXmlSerializable or add a property to TestClass and serialize that as an attribute:

public class TestClass
{
    [XmlIgnore]
    public PointXY Points { get; set; }

    [XmlAttribute("Points")]
    public string PointString
    {
        get
        {
            return string.Format("{0} {1}",Points.X, Points.Y);
        }
        set
        {
            // TODO:  Add null checking, validation, etc.
            string[] parts = value.Split(' ');
            Points = new PointXY {X = double.Parse(parts[0]), Y = double.Parse(parts[1])};
        }
    }
}

Complex objects are usually serialized as XML elements. Unfortunately you cannot set XmlAttribute on complex type, otherwise you will get a runtime exception. If you absolutely must use Xml attribute here, you can create a dummy property which will return only the data that you need. Use this code:

public class TestClass
{
    [XmlAttribute(@"Points")]
    public string PointsString
    {
        get { return Points.ToString(); }
        set { throw new NotSupportedException(); }
    }

    [XmlIgnore]
    public PointXY Points { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM