views:

54

answers:

2

Hi All,

I have to dynamically assign and change complex objects attributes at run time using the System.Xml.Serialization.XmlAttributeOverrides

So far I have been able to do everything i needed.

My one question is how can I iterate through the collection to see what has already been added?

And if I can't interate through this collection, can I join two XmlAttributeOverrides collection to form one complete one.

Thanks

A: 

Not conveniently, no.

You can get values for types you expect by using the indexer - either yourOverrides[type] or yourOverrides[type, memberName] - but to get a list of all the data inside would require reflection (it isn't exposed on the API).

By inspection (although this is brittle), there is a field called types that is a Hashtable (keyed by Type). Each object in the Hashtable is itself a Hashtable (keyed by member-name, with "" for the type's own settings).

Good luck, and don't blame me if it falls in a big heap when you apply some hotfix or new .NET version...

Marc Gravell
A: 

You could create an XmlAttributeOverridesBuilder class, similar to XmlAttributeOverrides, which will give you better control over the XmlAttributes it contains. That way, you could work on XmlAttributeOverridesBuilder instances, combine them if necessary, and call a GetOverrides method when you need the actual XmlAttributeOverrides instance.

public class XmlAttributeOverridesBuilder
{
    private Dictionary<Type, Dictionary<string, XmlAttributes>> _entries;

    public XmlAttributeOverridesBuilder()
    {
        _entries = new Dictionary<Type, Dictionary<string, XmlAttributes>>();
    }

    public void Add(Type type, XmlAttributes attributes)
    {
        Add(type, String.Empty, attributes);
    }

    public void Add(Type type, string member, XmlAttributes attributes)
    {
        Dictionary<string, XmlAttributes> typeEntries;
        if (!_entries.TryGetValue(type, out typeEntries))
        {
            typeEntries = new Dictionary<string, XmlAttributes>();
            _entries[type] = typeEntries;
        }
        typeEntries[member] = attributes;
    }

    public XmlAttributeOverrides GetOverrides()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        foreach(var kvpType in _entries)
        {
            foreach(var kvpMember in kvpType.Value)
            {
                overrides.Add(kvpType.Key, kvpMember.Key, kvpMember.Value);
            }
        }
        return overrides;
    }

    public XmlAttributeOverridesBuilder Combine(XmlAttributeOverridesBuilder other)
    {
        // combine logic to build a new XmlAttributeOverridesBuilder
        // ...
    }
}
Thomas Levesque