禁用特定属性的序列化

时间:2011-05-26 15:37:06

标签: c# serialization xml-serialization

我有一个XML序列化的类对象

[XmlType("PAYMENT")]
public class PaymentXML
{
    [XmlElement(ElementName = "REQUEST")]
    public RequestXML Request { get; set; }

    [XmlElement(ElementName = "META")]
    public MetaXML Request { get; set; }

    //Property that I dont want to be serialized
    public Subscriber Subscriber { get; set; }
}

序列化

var xml = new PaymentXML();

string path = HttpContext.Current.Server.MapPath(@_xmlResponseDir + _responsePath);

using (var sw = new StreamWriter(path))
{
    var ns = new XmlSerializerNamespaces();
    ns.Add("", "");

    var serializer = new XmlSerializer(typeof(PaymentXML), new XmlRootAttribute("XML"));

    serializer.Serialize(sw, xml, ns);
}

问题是,它还序列化Subscriber属性。我只希望将RequestXMLMetaXML序列化为XML。 如何在序列化过程中排除Subscriber属性?

2 个答案:

答案 0 :(得分:30)

使用[XmlIgnore]属性:

// Property that I don't want to be serialized.
[XmlIgnore]
public Subscriber Subscriber { get; set; }

答案 1 :(得分:9)

XmlIgnore属性添加到该属性。