代码之家  ›  专栏  ›  技术社区  ›  Richard Ev

了解带有基类的System.Xml.Serialization.XmlIgnoreAttribute

  •  1
  • Richard Ev  · 技术社区  · 14 年前

    我有两个班,如下所示:

    [Serializable]
    [XmlInclude(typeof(SomeDerived))]
    public class SomeBase
    {
        public string SomeProperty { get; set; }
    }
    
    public class SomeDerived : SomeBase
    {
        [XmlIgnore]
        public new string SomeProperty { get; set; }
    }
    

    SomeDerived 我不希望看到它的价值 SomeProperty . 不过,我知道。我试过其他方法,比如 virtual 在里面 SomeBase . 我仍然在的序列化实例中看到它 一些衍生的 .

    有人能解释一下这是怎么回事吗 XmlIgnoreAttribute ?

    为了完整起见,我的反序列化代码如下

    class Program
    {
        static void Main(string[] args)
        {
            SomeDerived someDerived = new SomeDerived { SomeProperty = "foo" };
    
            XmlSerializer ser = new XmlSerializer(typeof(SomeBase));
    
            MemoryStream memStream = new MemoryStream();
            XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Default);
            ser.Serialize(memStream, someDerived);
    
            xmlWriter.Close();
            memStream.Close();
            string xml = Encoding.Default.GetString(memStream.GetBuffer());
    
            Console.WriteLine(xml);
            Console.ReadLine();
        }
    }
    

    编辑

    如果将序列化程序声明更改为 new XmlSerializer(typeof(SomeDerived)) .

    1 回复  |  直到 14 年前
        1
  •  3
  •   Wallace Breza    14 年前

    试试这个。它使用XmlSerializer构造函数上的重写传入一些序列化重写:

    SomeDerived someDerived = new SomeDerived { SomeProperty = "foo" };
    
    // Create the XmlAttributeOverrides and XmlAttributes objects.
    XmlAttributeOverrides overrides = new XmlAttributeOverrides();
    XmlAttributes attrs = new XmlAttributes();
    
    /* Use the XmlIgnore to instruct the XmlSerializer to ignore
        the GroupName instead. */
    attrs = new XmlAttributes();
    attrs.XmlIgnore = true;
    overrides.Add(typeof(SomeBase), "SomeProperty", attrs);
    
    XmlSerializer ser = new XmlSerializer(typeof(SomeBase), overrides);
    
    MemoryStream memStream = new MemoryStream();
    XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Default);
    ser.Serialize(memStream, someDerived);
    
    xmlWriter.Close();
    memStream.Close();
    string xml = Encoding.Default.GetString(memStream.GetBuffer());