2017-02-04 3 views
1

を働いていない要素を無視するXmlAttributeOverridesを使用した:私は唯一のシリアル化の要素のいくつかを無視するように次のことをやっている

public class Parent 
{ 
    public SomeClass MyProperty {get;set;} 
    public List<Child> Children {get;set;} 
} 

public class Child 
{ 
    public SomeClass MyProperty {get;set;} 
} 

public class SomeClass 
{ 
    public string Name {get;set;} 
} 

XmlAttributes ignore = new XmlAttributes() 
{ 
    XmlIgnore = true 
}; 

XmlAttributeOverrides overrides = new XmlAttributeOverrides(); 
overrides.Add(typeof(SomeClass), "MyProperty", ignore); 

var xs = new XmlSerializer(typeof(MyParent), overrides); 

クラスのプロパティはXmlElement属性を表示できません。プロパティ名は、overrides.Addに渡される文字列にも一致します。

しかし、上記はプロパティを無視しておらず、まだシリアル化されています。

私には何が欠けていますか?

+0

コード例では、 'MyParent'は' Parent'ですか? – dbc

答えて

1

XmlAttributeOverrides.Add(Type type, string member, XmlAttributes attributes)に渡すタイプは、メンバーが返すタイプではありません。メンバーはと書かれたタイプで、と宣言されています。あなたが上書きしてXmlSerializerを構築する場合、あなたは深刻なメモリリークを回避するために静的にそれをキャッシュしなければならない、ということ

XmlAttributes ignore = new XmlAttributes() 
{ 
    XmlIgnore = true 
}; 

XmlAttributeOverrides overrides = new XmlAttributeOverrides(); 
//overrides.Add(typeof(SomeClass), "MyProperty", ignore); // Does not work. MyProperty is not a member of SomeClass 
overrides.Add(typeof(Parent), "MyProperty", ignore); 
overrides.Add(typeof(Child), "MyProperty", ignore); 

xs = new XmlSerializer(typeof(Parent), overrides);   

注:このようにあなたがしなければならないの両方ParentChildMyPropertyを無視します。詳細については、Memory Leak using StreamReader and XmlSerializerを参照してください。

サンプルfiddle

関連する問題