简体   繁体   中英

Is it possible to add XmlIgnore attribute in derived classes?

I have class Animal and classes Dog and Cat inheriting from it. Class Animal has property X. I would like to generate XML for "Dog" without "X" property and for "Cat" with "X" property. XmlIgnore doesn't work here in the way I expected.

I tried to use virtual property and then override it in derived class but it didn't work.

class Program
{
    static void Main(string[] args)
    {
        Dog dog = new Dog();
        Cat cat = new Cat();

        SerializeToFile(dog, "testDog.xml");
        SerializeToFile(cat, "testCat.xml");
    }

    private static void SerializeToFile(Animal animal, string outputFileName)
    {
        XmlSerializer serializer = new XmlSerializer(animal.GetType());

        TextWriter writer = new StreamWriter(outputFileName);
        serializer.Serialize(writer, animal);
        writer.Close();
    }
}
public abstract class Animal
{
    public virtual int X { get; set; }
}
public class Dog : Animal
{
    [XmlIgnore]
    public override int X { get; set; }
}
public class Cat : Animal
{
    public override int X { get; set; }
}

Even though you don't need this anymore, I still found the solution to this problem.

You can create XmlAttributeOverrides and set the XmlAttributes.XmlIgnore Property for certain fields of classes.

private static void SerializeToFile(Animal animal, string outputFileName)
{
    // call Method to get Serializer
    XmlSerializer serializer = CreateOverrider(animal.GetType()); 
    TextWriter writer = new StreamWriter(outputFileName);
    serializer.Serialize(writer, animal);
    writer.Close();
}

// Return an XmlSerializer used for overriding.
public XmlSerializer CreateOverrider(Type type)
{
    // Create the XmlAttributeOverrides and XmlAttributes objects.
    XmlAttributeOverrides xOver = new XmlAttributeOverrides();
    XmlAttributes attrs = new XmlAttributes();

    /* Setting XmlIgnore to true overrides the XmlIgnoreAttribute
     applied to the X field. Thus it won't be serialized.*/
    attrs.XmlIgnore = true;
    xOver.Add(typeof(Dog), "X", attrs);

    XmlSerializer xSer = new XmlSerializer(type, xOver);
    return xSer;
}

Of course you can also do the opposite by setting attrs.XmlIgnore to false .

Check this out for more information.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM