开发者

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] attri开发者_运维百科bute.


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, i.e.

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.


you can put [XmlIgnore] attribute on all members you do not want to be serialized.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜