Is it possible to serialize property attributes to XML attributes in C#?
Background: This question is about logging the change tracking of a POCO class in C# .NET 4.0.
Let's say I have a Person class with a Name (string) property. That Name property has a custom Attribute called [IsDirty(true/false)] that is set dynamically by a property-auditing class.
[IsDirty(true)]
public string Name { get; set; }
After the changes are detected and the attributes are set, I'm stori开发者_JAVA技巧ng the object via normal XML Serialization in a MS SQL Database (XML column type).
What I can't figure out is if it's possible to somehow serialize my custom attribute IsDirty along with it's current value - preferably as an XML attribute on the serialized XML element (Name) so that the final xml is like:
<Name IsDirty="true">John</Name>
Any ideas/info would be appreciated-
I think you're going to have to write your own XML serialization for this and mix in some reflection to check attribute values on properties.
There's a good guide to implementing the IXMLSerializable
interface here. Unfortunately you will have to implement serialization of all properties in the class, but on the bright side, if you implement IXmlSerializable
correctly, you can still use the XmlSerializer
class.
In your serialization code, you can check the attribute value using something like this:
public class YourClass : IXmlSerializable
{
[IsDirty(true)]
public string Name { get; set; }
// skipped ReadXml and GetSchema interface methods for brevity
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("YourClass");
var myType = typeof(YourClass);
foreach(var propInfo in myType.GetProperties())
{
writer.WriteStartElement(propInfo.Name);
foreach(var attr in propInfo.GetCustomAttributes(typeof(IsDirtyAttribute), false))
{
var myAttr = attr as IsDirtyAttribute;
writer.WriteAttributeString("Dirty", attr.Value ? "true" : "false");
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
This code is untested and written from memory, so there are probably some bugs lurking around, but hopefully it'll get you on the right track.
It would be possible by manually reading your Attribute and its value. You could do this by wrapping the serialization and deserialization in methods that appended/read the to/from the xml and the attribute..
However I would inherit these classes from a base class that had the property IsDirty then you neednt worry!
精彩评论