Serialize nullable type to optional non-nillable element

前端 未结 2 1715
时光说笑
时光说笑 2021-01-18 22:35

I have an xsd schema with an optional element (minOccurs=0, maxOccurs=1) of type int. The element is NOT defined as nillable. In the d

2条回答
  •  长情又很酷
    2021-01-18 22:57

    I am not sure about XxxSpecified, but you can use the ShouldSerializeXxx methods. These happily work whether the property type is nullable or not. The following should do the job:

    public int? Property { get ; set ; }
    
    // this member is used for XML serialization
    public bool ShouldSerializeProperty () { return Property.HasValue ; }
    

    As for the generation of code from XSD schema, if you're using Microsoft's xsd.exe tool the best bet seems to be to post-process the generated assembly with e.g. Mono.Cecil to modify the types of the properties of interest and to insert any extra serialization-related members like ShouldSerializeXxx. Adding an XSLT pre-processing step to run xsd.exe on a 'fixed' schema with nillable element declarations achieves the first goal, but not the second. xsd.exe is not flexible enough to do what you want. You might also try adding this functionality to xsd2code, since it's open-source.

提交回复
热议问题