使用XmlSerializer忽略.NET中Xml序列化中属性的属性

时间:2013-07-30 13:11:31

标签: c# .net serialization xml-serialization xmlserializer

我正在使用XmlSerializer执行Xml血清化。我正在执行ClassA的序列化,其中包含MyProperty类型的ClassB属性。我不希望序列化ClassB的特定属性。

我必须使用XmlAttributeOverrides,因为这些类在另一个库中。 如果该属性本身位于ClassA,则可能很简单。

XmlAttributeOverrides xmlOver = new XmlAttributeOverrides();
XmlAttributes xmlAttr = new XmlAttributes();
xmlAttr.XmlIgnore = true;
xmlOver.Add(typeof(ClassA), "MyProperty", xmlAttr);

XmlSerializer ser = new XmlSerializer(typeof(ClassA), xmlOver);

如果属性位于ClassB并且我们需要序列化ClassA,如何完成?

1 个答案:

答案 0 :(得分:5)

你几乎得到了它,只需更新你的替换指向ClassB而不是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);

快速测试,给出:

public class ClassA
{
    public ClassB MyProperty { get; set; }
}

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

导出方法:

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

主要方法:

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

    Console.WriteLine(ToXml(classA));
}

省略“ThePropertyNameToIgnore”输出:

<?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>