If you are using XmlSerializer, you can control whether the value is emitted by including a PropertyNameSpecified property.
Another option is to use a special
pattern to create a Boolean field
recognized by the XmlSerializer, and
to apply the XmlIgnoreAttribute to the
field. The pattern is created in the
form of propertyNameSpecified. For
example, if there is a field named
"MyFirstName" you would also create a
field named "MyFirstNameSpecified"
that instructs the XmlSerializer
whether to generate the XML element
named "MyFirstName".
For example, if you declare the class like this:
public class Data
{
[XmlIgnore]
public bool CLS_CDSpecified { get; set; }
[XmlElement(IsNullable=true)]
public string CLS_CD { get; set; }
}
Then you can serialize nothing, an explicit nil value, or an actual value:
var serializer = new XmlSerializer(typeof(Data));
var serializesNothing = new Data();
serializesNothing.CLS_CD = null;
serializesNothing.CLS_CDSpecified = false;
serializer.Serialize(Console.Out, serializesNothing);
Console.WriteLine();
Console.WriteLine();
var serializesNil = new Data();
serializesNil.CLS_CD = null;
serializesNil.CLS_CDSpecified = true;
serializer.Serialize(Console.Out, serializesNil);
Console.WriteLine();
Console.WriteLine();
var serializesValue = new Data();
serializesValue.CLS_CD = "value";
serializesValue.CLS_CDSpecified = true;
serializer.Serialize(Console.Out, serializesValue);
Output:
<?xml version="1.0" encoding="IBM437"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
<?xml version="1.0" encoding="IBM437"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CLS_CD xsi:nil="true" />
</Data>
<?xml version="1.0" encoding="IBM437"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CLS_CD>value</CLS_CD>
</Data>