Reputation: 796
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.
Upvotes: 0
Views: 135
Reputation: 24916
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; }
}
Upvotes: 0
Reputation: 152624
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])};
}
}
}
Upvotes: 1