Ignore property of a property in Xml Serialization in .NET using XmlSerializer

前端 未结 1 508
再見小時候
再見小時候 2021-01-20 00:53

I am carrying out Xml serrialization using XmlSerializer. I am carrying out serialization of ClassA, which contains property named MyProperty

1条回答
  •  余生分开走
    2021-01-20 01:23

    You almost got it, just update your overrides to point to ClassB instead of ClassA:

    XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
    XmlAttributes xmlAttr = new XmlAttributes();
    xmlAttr.XmlIgnore = true;
    
    //change this to point to ClassB's property to ignore
    xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr);
    
    XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);
    

    Quick test, given:

    public class ClassA
    {
        public ClassB MyProperty { get; set; }
    }
    
    public class ClassB
    {
        public string ThePropertyNameToIgnore { get; set; }
        public string Prop2 { get; set; }
    }
    

    And exporting method:

    public static string ToXml(object obj)
    {
        XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
        XmlAttributes xmlAttr = new XmlAttributes();
        xmlAttr.XmlIgnore = true;
        xmlOver.Add(typeof(ClassB), "ThePropertyNameToIgnore", xmlAttr);
    
    
        XmlSerializer xs = new XmlSerializer(typeof(ClassA), xmlOver);
        using (MemoryStream stream = new MemoryStream())
        {
            xs.Serialize(stream, obj);
            return System.Text.Encoding.UTF8.GetString(stream.ToArray());
        }
    }
    

    Main method:

    void Main()
    {
        var classA = new ClassA {
            MyProperty = new ClassB {
                ThePropertyNameToIgnore = "Hello",
                Prop2 = "World!"
            }
        };
    
        Console.WriteLine(ToXml(classA));
    }
    

    Outputs this with "ThePropertyNameToIgnore" omitted:

    
    
      
        World!
      
    
    

    0 讨论(0)
提交回复
热议问题