droyo / go-xml

utility and code-generation libraries for XML
MIT License
304 stars 115 forks source link

Use pointer type for nillable elements #146

Closed cbart closed 1 year ago

cbart commented 2 years ago

Use pointer type for nillable elements as described in xsd.Element.Nillable.

This allows in defining a recursive complexType, like so:

<xs:complexType name="composite">
  <xs:choice>
    <xs:element name="leaf" nillable="true" minOccurs="0">
      <xs:complexType/>
    </xs:element>
    <xs:element name="delegate" type="composite" nillable="true" minOccurs="0"/>
  </xs:choice>
</xs:complexType>

Otherwise the above results in generating (xml annotations removed for brevity):

type Leaf struct {}
type Composite struct {
  Leaf Leaf
  Delegate Composite
}

The above cannot compile. Composite struct contains itself which would result in infinite expansion of the struct.

Instead, when introducing a pointer of a nillable element:

type Leaf struct {}
type Composite struct {
  Leaf *Leaf
  Delegate *Composite
}

The above compiles.

The example using pointers also matches Go pattern of using nil to explicitly mark absence where only some of many values are expected (semantics of xs:choice).