I'm doing the following to ignore a couple of elements on serialization only:
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);
The class properties do not have the XmlElement
attribute. The property name also matches the string passed to overrides.Add
.
However, the above is not ignoring the property and it's still serialized.
What am I missing?
The type to pass in to XmlAttributeOverrides.Add(Type type, string member, XmlAttributes attributes)
is not the type that the member returns. It's the type in which the member is declared . Thus to ignore MyProperty
in both Parent
and Child
you must do:
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);
Note that, if you construct an XmlSerializer
with overrides, you must cache it statically to avoid a severe memory leak. See Memory Leak using StreamReader and XmlSerializer for details.
Sample fiddle .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.