简体   繁体   中英

Serialize nullable enum wcf

I 've problem with serialize my enum to nullable enum. I would like to make enum as a nullable with minoccurs = 0.

Here's my enum:

public enum TestEnum
{
    val_1= 0,
    val_2 = 1,
    val_3 = 2,
    val_4 = 3
}

I've tried serialize as a string or with "spefified" flag but it's use only for boolean values.

So finally I want to get xsd like this:

<element minOccurs="0" maxOccurs="1" name="TestEnum" type="TestEnum"/>

I always get minOccurs="1"

I didn't love this solution but i've found a workaround

public enum MyEnum
{
    Val1,
    Val2,
}

public class TestDefine
{
    public string MyEnumPropSerialize
    {
        get
        {
            if (MyEnumProp.HasValue)
            {
                return MyEnumProp.ToString();
            }
            return null;
        }
        set
        {
            MyEnum importValue;
            if (Enum.TryParse<MyEnum>(value, out importValue))
            {
                MyEnumProp = importValue;
            }else
            {
                MyEnumProp.ToString();
            }
        }
    }

    [XmlIgnore]
    public MyEnum? MyEnumProp { get; set; }
}

this class, when you execute xsd.exe create this xsd definition

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="TestDefine" nillable="true" type="TestDefine" />
  <xs:complexType name="TestDefine">
    <xs:sequence>
      <xs:element minOccurs="0" maxOccurs="1" name="MyEnumPropSerialize" type="xs:string" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

It's correct XSD but i've inserted one property "fake" to force XSD generator to create XSD as you want.

I think than if XSD.exe generator don't meet your requirements you need to customize itself or create XSD manually. After that you can implement IXmlSerializer method on your object so you'll get full control on deserialization and XML parsing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM