Ignore property property in Xml Serialization in .NET with XmlSerializer

I am doing Xml serialization using XmlSerializer . I am serializing ClassA , which contains a property named MyProperty type ClassB . I do not want to serialize a specific ClassB property.

I need to use XmlAttributeOverrides since the classes are in a different library. If the property was in ClassA , that would be easy.

 XmlAttributeOverrides xmlOver = new XmlAttributeOverrides(); XmlAttributes xmlAttr = new XmlAttributes(); xmlAttr.XmlIgnore = true; xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr); XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver); 

How to execute if the property is in ClassB and we need to serialize ClassA ?

+4
source share
1 answer

You almost got it, just update your overrides by pointing to ClassB instead of ClassA :

 XmlAttributeOverrides xmlOver = new XmlAttributeOverrides(); XmlAttributes xmlAttr = new XmlAttributes(); xmlAttr.XmlIgnore = true; //change this to point to ClassB property to ignore xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr); XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver); 

A quick test if:

 public class ClassA { public ClassB MyProperty { get; set; } } public class ClassB { public string ThePropertyNameToIgnore { get; set; } public string Prop2 { get; set; } } 

And export method:

 public static string ToXml(object obj) { XmlAttributeOverrides xmlOver = new XmlAttributeOverrides(); XmlAttributes xmlAttr = new XmlAttributes(); xmlAttr.XmlIgnore = true; xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr); XmlSerializer xs = new XmlSerializer(typeof(ClassA), xmlOver); using (MemoryStream stream = new MemoryStream()) { xs.Serialize(stream, obj); return System.Text.Encoding.UTF8.GetString(stream.ToArray()); } } 

The main method:

 void Main() { var classA = new ClassA { MyProperty = new ClassB { ThePropertyNameToIgnore = "Hello", Prop2 = "World!" } }; Console.WriteLine(ToXml(classA)); } 

Outputs this using the parameter "ThePropertyNameToIgnore":

 <?xml version="1.0"?> <ClassA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MyProperty> <Prop2>World!</Prop2> </MyProperty> </ClassA> 
+4
source

Source: https://habr.com/ru/post/1494290/


All Articles