2017-02-04 18 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)的類型不是會員返回的類型。這是成員宣稱爲的類型。因此,忽略這兩個ParentMyPropertyChild你必須做到:

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);   

需要注意的是,如果你構建具有覆蓋的XmlSerializer,你必須靜態緩存,以避免嚴重的內存泄漏。詳情請參閱Memory Leak using StreamReader and XmlSerializer

樣品fiddle