I am using complex types in order to support serialization/deserialization
of floating point numbers, since floating points can't be null.
I've seen how to suppress attributes that are "not specified", such as
having a float member called Value, and a bool member called ValueSpecified.
This instructs the XML Serializer to omit that attribute altogether if it
wasn't "Specified". But how can I tell it to omit the XML element
altogether?
Here's the problem:
I deserialize an object that looks like this:
<person>
<name>Joe</name>
<age>37</age>
</person>
When deserialized, I get an object of type person, with a field age of type
floatType which has Value = 37 and ValueSpecified = false.
If I change name to "Bob" (p.name = "Bob"), and then immediately serialize
that object to XML, I get:
<person>
<name>Bob</name>
<age />
</person>
This indicates that age should now be null (if I pass this off to a SOAP
server for instance), or if that value is not allowed to be nulled, then I
get a SOAP exception.
If I explicitly set p.age.ValueSpecified = true or set p.age.Value = 36
(which implicitly sets ValueSpecified to true)
Then I get the expected
<person>
<name>Bob</name>
<age>36</age>
</person>
What I would like to see happen is if ValueSpecified is false, then just
leave that element off altogether. Is there a way to do this?
Here's what the generated code for the objects looks like:
[XmlType(TypeName="floatType",Namespace=Declaration s.SchemaVersion),XmlRoot,Serializable]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public class floatType
{
[XmlAttribute(AttributeName="value",Form=XmlSchemaF orm.Unqualified,DataType="string",Namespace=Declar ations.SchemaVersion)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public string __value;
[XmlIgnore]
public string @value
{
get { return __value; }
set { __value = value; }
}
[XmlText(DataType="float")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public float __Value;
[XmlIgnore]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool __ValueSpecified;
[XmlIgnore]
public float Value
{
get { return __Value; }
set { __Value = value; __ValueSpecified = true; }
}
public floatType()
{
}
public void MakeSchemaCompliant()
{
}
public static event DepthFirstTraversalDelegate DepthFirstTraversalEvent;
public void DepthFirstTraversal(object parent, object context)
{
if (DepthFirstTraversalEvent != null) DepthFirstTraversalEvent(this, parent,
context);
}
}
Here's the XSD that the code was generated from:
<xsd:complexType name="floatType">
<xsd:simpleContent>
<xsd:extension base="xsd:float">
<xsd:attribute name="value" type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
Thanks for your help