使用.NET的XmlSerializer时忽略派生类的属性

我有一个基类,它有一个虚拟属性和一个覆盖虚拟属性的派生类型 . 该类型可以序列化为XML . 我想要做的是当对象是派生类型时,不要持久于项目列表属性 . 为了实现这一点,派生类使用 [XmlIgnore] 属性修饰了重写属性 . 基类中的虚拟属性不适用 XmlIgnore 属性 . 由于某种原因,即使对象属于派生类型( DynamicCart ),项目列表也会被序列化 .

当我将 XmlIgnore 属性应用于基类中的虚拟属性时,列表不会被序列化为文件 .

public class ShoppingCart
{  
   public virtual List<items> Items{get; set;}

   //and other properties 

   public void SerializeToXML (string filePath)
   {
     var xmlSerializer = new XmlSerializer(this.GetType());
     textWriter = new System.IO.StreamWriter(filePath);
     xmlSerializer.Serialize(textWriter, this);
     textWriter.Flush();
     textWriter.Close();  
   }
}

//A cart that is populated by algo based on parameters supplied by user. I have no need to
//persist the actual items across sessions.
class DynamicCart: ShoppingCart
{
   [XmlIgnore]
   public override List<items>{get;set;}
   //and other properties 
}

class Shop
{
   ShoppingCart cart = new DynamicCart();
   PopulateCart(cart);
   cart.serializeToXML(<PATH TO FILE>);
}

回答(4)

2 years ago

我认为你的序列化程序使用你的基类而不是派生类 .

public void SerializeToXML(string filePath, Type type)
{
    xmlSerializer = new XmlSerializer(type);
    textWriter = new System.IO.StreamWriter(filePath);
    xmlSerializer.Serialize(textWriter, this);
    textWriter.Flush();
    textWriter.Close();
}

class Shop
{
    ShoppingCart cart= new DynamicCart();
    PopulateCart(cart);
    cart.serializeToXML(<PATH TO FILE>, typeof(DynamicCart));
}

2 years ago

您可以通过向基类添加虚拟 ShouldSerialize*** 方法来完成此操作 . 例如:

[XmlInclude(typeof(Sub))]
public class Base
{
    public virtual string Prop { get; set; }

    public virtual bool ShouldSerializeProp() { return true; }
}

public class Sub : Base
{
    public override string Prop { get; set; }

    public override bool ShouldSerializeProp() { return false; }
}

internal class Program
{
    private static void Main()
    {
        var o = new Sub { Prop = "Value" };

        var baseSer = new XmlSerializer(typeof (Base));
        var subSer = new XmlSerializer(typeof (Sub));

        Console.Out.WriteLine("BASE:");
        baseSer.Serialize(Console.Out, o);
        Console.Out.WriteLine();

        Console.Out.WriteLine("SUB:");
        subSer.Serialize(Console.Out, o);
        Console.Out.WriteLine();

        Console.ReadLine();
    }
}

这产生(略微整理):

BASE:
<Base xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Sub">
  <Prop>Value</Prop>
</Base>

SUB:
<Sub />

该方法必须包含 ShouldInclude... 之后要考虑的属性的确切名称 .

2 years ago

我想你需要在XML类序化的基类中声明派生类型 . 听起来有点傻,但是符合规范 .

请参阅MSDN page,并查找以下示例:

[System.Xml.Serialization.XmlInclude( typeof( Derived ) )]
public class Base
{
    // ...
}

2 years ago

试试这个

XmlSerializer serializer = new XmlSerializer(typeof(DynamicCart), new Type[]{typeof(ShoppingCart)});

这将允许您添加尽可能多的类型,您希望序列化器包含在内 .