简体   繁体   中英

serialize only one property of a class

I have a class which have about 20 members. I need to serialize my the object of this class in a XML. But condition is I need only one member in the XML.

How can I do this.

EDIT : But at some time, I would like to serialize all the members. So I can't use [XMLIgnore] attribute.

Add the following attribute for all the members you don't want to serialize,

[XmlIgnore()]
public Type X
{
get;set;
}

You could explicitly implement the IXmlSerializable interface and control the reading/writing of the fields yourself, based on some external parameter, ie

class CustomXml: IXmlSerializable
{
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        //
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        if (SerializationParameter.FullSerialization)
           //deserialize everything
        else
           //deserialize one field only
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        if (SerializationParameter.FullSerialization)
           //serialize everything
        else
           //serialize one field only
    }
}

where SerializationParameter.FullSerialization is an example of how you could control what is serialized when.

您可以将[XmlIgnore]属性放在您不想序列化的所有成员上。

There is two ways to make properties non-serializable in.NET using attributes.

You may set attributes [NonSerialized] or [XmlIgnore]

If you serializing in binary or SOAP you should use [NonSerialized] , if you want to serialize just in XML you should use [XmlIgnore] .

So in your case the answer is [XmlIgnore]

EDIT: There is no way to apply attributes to properties dynamically. Here some info about that here: Can attributes be added dynamically in C#? and here Remove C# attribute of a property dynamically

Also as a workout you may have different copies of your class with different attributes.

OR

Have a copy of your class set all props as serializable but populate only properties you need, this way every thing else will be null/empty and after serialization of that class you should get the XML you need.

mark the other attributes

<NonSerializable()> _
Property someproperty

End Property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM