Reputation: 65
To communicate with a web API, I have created a few classes which will be serialized to XML and sent to the API. The API only accepts these XMLs if they only hold properties with non-default values.
How can I leave out properties during serialization?
Suppose I have a class as follows (simplified example):
[XmlRoot("SomeData")]
public class SomeData
{
[XmlElement("rangeX")]
public int RangeX { get; set; }
[XmlElement("rangeY")]
public int RangeY { get; set; }
[XmlElement("rangeZ")]
public int RangeZ { get; set; }
}
An object which has a non-default value for RangeX and RangeY should thus be serialized to an XML which only holds tags for rangeX and rangeY.
I have found how to leave out null values, but this is not what I want - the default value could very well be different from null.
Thanks!
Upvotes: 0
Views: 326
Reputation: 26436
You can use the "secret" ShouldSerializeXxx() method:
public bool ShouldSerializeRangeX()
{
return RangeX != someDefaultValue;
}
There are a ton of examples when you search for ShouldSerialize Default Value, it's just hard to find if you don't know what you're looking for.
Here is a link to help get you started : Defining Default Values with the ShouldSerialize and Reset Methods
Upvotes: 3
Reputation: 14007
You can gain full control on how the objects of your class are serialized when you implement the IXmlSerializable
interface (only including the code to write the data, since that is your immediate question):
public class SomeData : IXmlSerializable
{
public int RangeX { get; set; }
public int RangeY { get; set; }
public int RangeY { get; set; }
public void WriteXml (XmlWriter writer)
{
writer.WriteStartElement("SomeData");
if (RangeX != 0)
{
writer.WriteElementString("rangeX", RangeX.ToTring());
}
if (RangeY != 0)
{
writer.WriteElementString("rangeY", RangeY.ToTring());
}
if (RangeZ != 0)
{
writer.WriteElementString("rangeZ", RangeZ.ToTring());
}
writer.WriteEndElement();
}
public void ReadXml (XmlReader reader)
{
//Implement if needed
throw new NotImplementedException();
}
public XmlSchema GetSchema()
{
return null;
}
}
Upvotes: 1