Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to hide an inherited data member?

I have two classes. The base class has a public property with a DataMember. Now, I do not want this property to be serialized in the child class. I have no control over the parent class, and several other classes do inherit from it.

Is there a way to "hide" this attribute from the XmlSerializer that's used by WCF ? (the context here is a WCF RESTful web service).

like image 532
xander Avatar asked Dec 02 '25 10:12

xander


1 Answers

Yes, it is possible using the XmlAttributeOverrides class, and the XmlIgnore property. Here is the example based on the one from MSDN:

public class GroupBase
{
    public string GroupName;

    public string Comment;
}

public class GroupDerived : GroupBase
{   
}

public class Test
{
   public static void Main()
   {
      Test t = new Test();
      t.SerializeObject("IgnoreXml.xml");
   }

   public XmlSerializer CreateOverrider()
   {
      XmlAttributeOverrides xOver = new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      attrs.XmlIgnore = true; //Ignore the property on serialization

      xOver.Add(typeof(GroupDerived), "Comment", attrs);

      XmlSerializer xSer = new XmlSerializer(typeof(GroupDerived), xOver);
      return xSer;
   }

   public void SerializeObject(string filename)
   {
      XmlSerializer xSer = CreateOverrider();

      GroupDerived myGroup = new GroupDerived();
      myGroup.GroupName = ".NET";
      myGroup.Comment = "My Comment...";

      TextWriter writer = new StreamWriter(filename);

      xSer.Serialize(writer, myGroup);
      writer.Close();
   }

Result:

<?xml version="1.0" encoding="utf-8"?>
<GroupDerived xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GroupName>.NET</GroupName>
</GroupDerived>

Result with XmlIgnore = false;:

<?xml version="1.0" encoding="utf-8"?>
<GroupDerived xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GroupName>.NET</GroupName>
  <Comment>My Comment...</Comment>
</GroupDerived>
like image 51
BartoszKP Avatar answered Dec 04 '25 00:12

BartoszKP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!