How to exclude certain properties in gerilization



  • I'm trying to show the object with a few properties, but I don't want to turn all the properties on the show.

    Of course I could use an attribute. [XmlIgnore]but I need to be able to do

    The question is how to exclude certain properties when servilization does not change the reference class, and it would be desirable to have a rigorous typology.

    Thank you.



  • This can be done as follows.

    We'll use the ready class. XmlAttributeOverrides but we'll do a couple of extension techniques to add strict typology:

    public static class XmlAttributeOverridesHelpers
    {
        public static void Add<T>(this XmlAttributeOverrides overrides, Expression<Func<T, dynamic>> propertySelector, XmlAttributes attributes)
        {
            overrides.Add(typeof(T), propertySelector.BuildString(), attributes);
        }
    
    public static string BuildString(this Expression propertySelector)
    {
        switch (propertySelector.NodeType)
        {
            case ExpressionType.Lambda:
                LambdaExpression lambdaExpression = (LambdaExpression)propertySelector;
                return BuildString(lambdaExpression.Body);
    
            case ExpressionType.Convert:
            case ExpressionType.Quote:
                UnaryExpression unaryExpression = (UnaryExpression)propertySelector;
                return BuildString(unaryExpression.Operand);
    
            case ExpressionType.MemberAccess:
    
                MemberExpression memberExpression = (MemberExpression)propertySelector;
                MemberInfo propertyInfo = memberExpression.Member;
    
                if (memberExpression.Expression is ParameterExpression)
                {
                    return propertyInfo.Name;
                }
                else
                {
                    // we've got a nested property (e.g. MyType.SomeProperty.SomeNestedProperty)
                    return BuildString(memberExpression.Expression) + "." + propertyInfo.Name;
                }
    
            default:
                // drop out and throw
                break;
        }
        throw new InvalidOperationException("Expression must be a member expression: " + propertySelector.ToString());
    }
    

    }

    May be applied as follows:

    var overrides = new XmlAttributeOverrides();
    var ignore = new XmlAttributes { XmlIgnore = true };
    overrides.Add<MyClass>(m => m.Id, ignore);
    overrides.Add<MyClass>(m => m.DateChanged, ignore);
    Type t = typeof(List<MyClass>);
    XmlSerializer serial = new XmlSerializer(t, overrides);

    The solution was found https://stackoverflow.com/a/9413711/5610621




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2