1
votes

Minoccurs is 0 in the XSD and nillable is true for an element.

But if I don't set the element value, it takes it as null and the record is blanked out on the server. Is there a way to tell it to omit the element from the output XML when some conditions are satisfied but have it for other cases?

 <xs:element name='CLS_CD' minOccurs='0' nillable='true' type='xdv:stringLen20'/>
1
Post your code/context, please.Hari Pachuveetil

1 Answers

2
votes

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>