1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
// La fonction de sérialisation
private void Serialize(MaClasseSerialisable o, string fileName, int v)
{
Type t = o.GetType();
XmlAttributeOverrides attrs = new XmlAttributeOverrides();
AddOverrideAttribute(attrs, t, v);
XmlSerializer xser = new XmlSerializer(t, attrs);
using (StreamWriter sw = new StreamWriter(fileName))
{
xser.Serialize(sw, configuration);
}
}
// --------------------------------------------------------
// Cette méthode construit récursivement les attributs de sérialisation
private void AddOverrideAttribute(XmlAttributeOverrides attributes, Type t, int vl)
{
if (t != null && attributes != null && attributes[t] == null)
{
XmlAttributes xattrs = new XmlAttributes();
//xattrs.XmlRoot = new XmlRootAttribute(t.Name);
//xattrs.XmlType = new XmlTypeAttribute(t.Name);
PropertyInfo[] props = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in props)
{
object[] attrs = p.GetCustomAttributes(typeof(UnAttributCustomAttribute), true);
if (attrs.Length == 1)
{
UnAttributCustomAttribute c = attrs[0] as UnAttributCustomAttribute;
if (c.Value == v)
{
xattrs.XmlElements.Add(new XmlElementAttribute(p.Name));
if(!p.PropertyType.IsValueType && p.PropertyType != typeof(string))
AddOverrideAttribute(attributes, p.PropertyType, level);
}
}
}
if(xattrs.XmlElements.Count > 0)
attributes.Add(t, xattrs);
}
} |
Partager