How to create your custom XmlAttribute Serialization
I'm looking on who to customize the serialization of an attribute. I thought it would be simple, but I was not able to achieve what I wanted to do the way I wanted.
So here is a simple example:
Class Definition:
Class MyClass
{
[XmlAttribute("myAttribute")]
public int[] MyProperty { get; set; }
}
Xml Result that I would like:
<MyClass myAttribute="1 2 3... N" />
The only work around I did to have that was to put a [XmlIgnore] attribute and create another property with some code that did the transformation.
So, my question, is there a better way than creating a new property? Maybe there is some kind of TypeConverter you can create so the serializer would use it?
Also, I've tried to use the Type attribute but without success. (Always getting exceptions). But from what I've read, it's for already defined datatype.
[XmlAttribute("myAttribute", typeof(MyConverter))]
public int[] MyProperty { get; set; }
Another interesting way would be like that:
[XmlAttribute("myAttribute")]
[XmlConverter(typeof(MyConverter))]
public int[] MyProperty { get; set; }
Thanks.
Edit Since no solution like 开发者_运维知识库I was looking for was presented, I finally decided to opt for the "IXmlSerializable" solution.
You can either:
- Implement
IXmlSerializable
and handle all the serialization/deserialization for your type manually Use a surrogate property:
[XmlIgnore] public int[] MyProperty { get; set; } [XmlAttribute("myAttribute")] public string _MyProperty { get { return string.Join(" ", MyProperty.Select(x => x.ToString()).ToArray()); } set { MyProperty = value.Split(' ').Select(x => int.Parse(x)).ToArray(); } }
精彩评论