5

I'm using XmlSerializer for WCF service (in the case of my service there are reasons for this). But recently I've encountered the problem: I cannot find a simple way to make a reference type property required, i.e. make it's definition in XSD look like this:

<xs:element minOccurs="1" maxOccurs="1" name="Name" type="xs:string"/>

instead of this:

<xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string"/>

Here is the code for property:

[XmlElement]
public string Name { get; set; }

I know that with DataContractSerializer I can do this:

[DataMember(IsRequired = true)]
public string Name { get; set; }

and I will get the desired schema.

Any ideas how to get the functionality similar to IsRequired's with XmlSerializer attributes?

Thanks.

Maksim Tyutmanov
  • 423
  • 1
  • 5
  • 12

2 Answers2

0

The way to go is to create or edit the XSD manually then use a validating XmlReader as the input to XmlSerializer.

Nick H
  • 154
  • 1
  • 4
0

Using

[XmlElement(IsNullable=true)]

should force the member to be serialized even when null, making it have a minOccurs of 1 (I think - haven't checked).

Rob Levine
  • 40,328
  • 13
  • 85
  • 111
  • You're right, it really sets minOccurs to 1 in xsd, but it also adds nillable="true" attribute to xs:element. What I want is to guarantee that client's message without this element wouldn't be accepted by the service so I wouldn't have to check the corresponding property for null. – Maksim Tyutmanov Feb 01 '12 at 07:11
  • I don;t think you can get the default xml serializer to force the element, without the extra attribute. Would it be an option to implement IXmlSerializable so you can fully customise the generated xml? – Rob Levine Feb 01 '12 at 10:54