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

三世轮回 提交于 2019-12-01 18:36:55

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:

<?xml version="1.0"?>
<ClassA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <MyProperty>
    <Prop2>World!</Prop2>
  </MyProperty>
</ClassA>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!