DCSIMG
November 2009 - Posts - Tamir Shlomi's Blog

Tamir Shlomi's Blog

Welcome to Tamir Shlomi's blog. All about .NET, OOP and SQL server

November 2009 - Posts

Override The XmlIgnoreAttribute When Using XmlSerializer

This post is about how to serialize type with properties that are decorated with XmlIgnoreAttribute (or any other XmlAttribute) using the XmlSerializer.

When we will try to serialize an instance of type that one or more of its properties marked with XmlIgnoreAttribute, it will be unsurprising to find out that those properties are not shown at the serialized XML.

We could just remove the XmlIgnoreAttribute from those properties, but what if the entity type declaration is out of our project scope or we can’t change it for some reason so the XmlIgnoreAttribute can’t be removed?

Nice solution for this issue is by using the XmlAttributeOverrides object which allows us to override an exist XmlAttributes and use it in order to create a new XmlSerializer that will be able to override those pre-defined attributes.

The XmlAttributeOverrides object will instantiate a new Hashtable that will contains all the attributes to be override, so when creating the XmlSerializer, we will pass the XmlAttributeOverrides as second argument.
Now, when serializing instance of that type, all the properties will be serialized, whether they decorated with XmlIgnoreAttribute or whether they aren’t.

Here is a code sample for creating XmlSerializer overrider that will serialize properties with XmlIgnoreAttribute:

public static XmlSerializer GetOverriderSerializer(Type entityType)
{
    // Create the XmlAttributeOverrides and XmlAttributes objects.
    XmlAttributeOverrides xmlOverrider = new XmlAttributeOverrides();
 
    // get the type of the XmlIgnoreAttribute for the LINQ query
    Type xmlIgnoreAttributeType = typeof(XmlIgnoreAttribute);
 
    // get all the property names which marks with XmlIgnoreAttribute
    IEnumerable<string> properties =
        from property in entityType.GetProperties()
        let attributes =
            property.GetCustomAttributes(xmlIgnoreAttributeType, true)
        where attributes.Count() > 0
        select property.Name;
 
    // assign XmlAttribute to override those fields with XmlIgnoreAttribute
    foreach (string propertyName in properties)
    {
        XmlAttributes xmlAttribute = new XmlAttributes
        {
            XmlIgnore = false
        };
 
        xmlOverrider.Add(entityType, propertyName, xmlAttribute);
    }
 
    // create the overrider serialzier
    XmlSerializer serializer = new XmlSerializer(entityType, xmlOverrider);
    return serializer;
}
 
Of course this code can be changed to override any other XmlAttribute.
 
Hope you find this helpful :-)
 
Tamir Shlomi