0

I have few classes with a number of properties. Value to these properties would be assigned based on certain conditions. After the values are assigned to few of the properties, I would like to serialize the object and include only those props that have value assigned to them.

I have tried searching for this on Internet but I could not find any luck.

Any suggestion on implementing this would be highly appreciated.

Update:

I have some classes like

class A{
        public static string PropA_in_A { get; set; }
        public string PropB_in_A { get; set; }
        public static string PropC_in_A { get; set; }
        public static string PropD_in_A { get; set; }
}

class B{
        public static string PropA_in_B { get; set; }
        public static string PropB_in_B { get; set; }
        public static string PropC_in_B { get; set; }
        public static string PropD_in_B { get; set; }
}

class C{
        public static string PropA_in_C { get; set; }
        public static string PropB_in_C { get; set; }
        public static string PropC_in_C { get; set; }
        public static string PropD_in_C { get; set; }
}

Values to the Properties in these classes need to assigned based on conditions. After the values are assigned , only those properties need to be serialized that have values assigned to them.

main()
{
A.PropB_in_A="Some Value";
A.PropA_in_B="Some Value";
A.PropC_in_C="Some Value";
}

Here , I would like to serialize only those properties have values assigned to them.

Rahul Vijayapuram
  • 53
  • 1
  • 1
  • 10
  • Possible duplicate of [Xml serialization - Hide null values](http://stackoverflow.com/questions/5818513/xml-serialization-hide-null-values) – Cᴏʀʏ Mar 02 '16 at 00:57
  • You may need to use propertyNameSpecified explained in: https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm and duplicated question in: https://stackoverflow.com/a/34322765/862795 – Rzassar Feb 07 '19 at 09:03

1 Answers1

0

You can use the XmlElementAttribute on each property and set IsNullable to false.

There is an example on MSDN here.

[XmlElementAttribute(IsNullable = false)]
public string City;

Or use the shorter form:

[XmlElement(IsNullable = false)]
public string City;

EDIT: For nullable value types, you have to jump through some extra hoops and add a property telling the serializer if it should serialize that value.

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

See this answer for reference: Xml serialization - Hide null values

Community
  • 1
  • 1
Matthew Jaspers
  • 1,546
  • 1
  • 10
  • 13