Link to home
Start Free TrialLog in
Avatar of rxraza
rxraza

asked on

XmlIgnore and overriding

I have a clsss B which derives from class A. In class B I have an XmlIgnore on a property 'PropA'. When I serialize the class using XmlSerialization it does not ignore PropA. If I put XmlIgnore on
the base class then it ignores that property but that is not what I want

public class A{
 private string _a;

 public virtual stirng PropA{
   get { return _a; }
  set { _a = value; }
 }
}

public class B : A{

[XmlIgnore]
public override string A{
   get { return _a; }
  set { _a = value; }
 }

}

B b = new B();
XmlSerializer serializer = new XmlSerializer(b.GetType());
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
serializer.Serialize(stringWriter, b);
striing xml = stringWriter.ToString();

Any ideas would be greatly appreicated.

Avatar of dstanley9
dstanley9

It may be a typo but in the base class your property is called PropA but in the derived class it's just called "A".  I''m assuming it's a typo since you don;t have a virtual property "A" to overrivde in B.

I don't know if you can define the classes that way since the resulting schems couldn't be defined.  However you could try adding overrides (see code example below)

In any case why would you want to serialize the property on the base class but not the inherited class?
XmlSerializer serializer; 
XmlAttributes attributes; 
XmlAttributeOverrides overrides; 
 
overrides = new XmlAttributeOverrides(); 
attributes = new XmlAttributes(); 
attributes.XmlIgnore = true; 
overrides.Add(typeof(A), "PropA", attributes); 
serializer = new XmlSerializer(typeof(B), overrides); 
 
B b = new B();
b.PropA = "propA";
TextWriter writer = new StreamWriter(@"C:\test.xml");
 
serializer.Serialize(writer, b);
writer.Close();

Open in new window

Avatar of rxraza

ASKER

dstanley9:

That is a typo. I tried your suggestion with overrides but no luck.

>> In any case why would you want to serialize the property on the base class but not the inherited >>class?

because the behavior has been overriden, hence may not be required when the object is serialized

My point is that the object that I am serializing is of type B and since type B has a property that has been marked to ignore so the XmlSerializer should obey the directives and not serialize the property found from the base class.

SOLUTION
Avatar of dstanley9
dstanley9

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial