Search code examples
c#xmlserializationxsdxmlserializer

primitive class being ignore when serializing xsd generated class


I used xsd.exe to generate a .cs class.

The xsd file as below

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="SendComments">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Input">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="TransId" maxOccurs="1" minOccurs="0" type="xs:string"/>
              <xs:element name="SampleId" minOccurs="0" maxOccurs="1" type="xs:long"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Output" type="xs:string" minOccurs="0"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

In my generated class, it has the correct field generated. However, when I call the serializer. The SampleId field being ignored.

Serializer code segment:

var serializer = new XmlSerializer(typeof(SendComments));
            using (StringWriter stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, SPCComment);
                return stringWriter.ToString();
            }

Result:

<?xml version="1.0" encoding="utf-16"?>
<SPCSendComments xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Input>
    <TransId>-</TransId>
  </Input>
</SPCSendComments>

I tried with other .xsd file, all the primitive type (bool, int, long) is being ignored when serializing.

I wonder what will be the cause that primitive type being ignored.


Solution

  • Your generated class has an extra field SampleIdSpecified that indicates if the field is null or not. Set that to true and the field will be serialized.

    If you set TransId to null, that will also be ignored.

    They're being ignored because they're optional fields in your schema. They have minOccurs = 0 which means that they don't need to be there for the XML to be valid.