Serializes only one class property

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

How can i do this.

EDIT . But at some point I would like to serialize all the members. Therefore, I cannot use the [XMLIgnore] attribute.

+4
source share
5 answers

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

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

You can explicitly implement the IXmlSerializable interface and independently control the reading / writing of fields 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 serialization when.

+2
source

you can put the [XmlIgnore] attribute for all members that you do not want to serialize.

+1
source

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

You can set the attributes [NonSerialized] or [XmlIgnore]

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

So in your case the answer is [XmlIgnore]

EDIT: Cannot apply dynamic attribute properties to properties. Here is some information about this here: Can dynamic attributes be added in C #? and here remove attribute c # properties dynamically

Just like training, you may have different copies of your class with different attributes.

OR

You have a copy of your class that defines all the details as serializable, but filling only the properties you need, so every thing will be empty / empty, and after serializing this class, you should get the necessary XML code.

+1
source

check other attributes

 <NonSerializable()> _ Property someproperty 

Final property

0
source

Source: https://habr.com/ru/post/1336127/


All Articles