c# - 是否可以在派生类中添加 XmlIgnore 属性?

标签 c# xml-serialization xmlignore

我有 Animal 类以及继承自它的 Dog 和 Cat 类。 Animal 类具有属性 X。 我想为没有“X”属性的“狗”和具有“X”属性的“猫”生成 XML。 XmlIgnore 在这里没有按我预期的方式工作。

我尝试使用虚属性,然后在派生类中重写它,但没有成功。

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; }
}

最佳答案

即使您不再需要它,我仍然找到了解决此问题的方法。

您可以创建 XmlAttributeOverrides 并为类的某些字段设置 XmlAttributes.XmlIgnore 属性。

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;
}

当然你也可以通过将attrs.XmlIgnore设置为false来做相反的事情。

检查 this了解更多信息。

关于c# - 是否可以在派生类中添加 XmlIgnore 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55614252/

相关文章:

c# - 第一次目录枚举太慢

c# - XslTransform 类在 .NET 转换后被弃用

c# - 当字符在 CDATA 中时,为什么 XML 序列化程序会抛出无效字符异常?

.net - 在复杂对象图上使用 IXmlSerializable 接口(interface)

c# - XmlIgnore 不起作用

c# - 忽略 XML 序列化中的空值

c# - 使用 System.Object 时实现对泛型方法的 new() 约束

c# - Paypal 更改默认货币

c# - 如何将元素反序列化为 XmlNode?

.net - XmlIgnoreAttribute,只在序列化时使用,反序列化时不使用?