Search code examples
xmlxsdxml-parsingxsd-validation

Can I make a type in xsd to be a choice without the parent element?


I have 2 types defined in my .xsd, IP and IPv6. I need to have an element in my .xml file so that it is either of those 2 types.

To do that I figured I might use xsd:choice but the problem is that it implies a parent element, e.g.:

<xs:element name="remote_ip">
  <xs:complexType>
    <xs:choice>
      <xs:element name="remote_ip" type="IP"/>
      <xs:element name="remote_ip" type="IPv6"/>
    </xs:choice>
  </xs:complexType>
</xs:element>

this allows me the following in the .xml:

<remote_ip>
  <remote_ip>10.0.0.1</remote_ip>
</remote_ip>

and I need the following:

<remote_ip>10.0.0.1</remote_ip>

IP and IPv6 types definitions:

<xs:simpleType name="IP">
  <xs:restriction base="xs:string">
   <xs:pattern value="([0-9]*\.){3}[0-9]*" />
  </xs:restriction>
 </xs:simpleType>
 <xs:simpleType name="IPv6">
   <xs:annotation>
     <xs:documentation>
       An IP version 6 address, based on RFC 1884.
     </xs:documentation>
   </xs:annotation>
   <xs:restriction base="xs:token">
     <!-- Fully specified address -->
     <xs:pattern value="[0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){7}"/>
     <!-- Double colon start -->
     <xs:pattern value=":(:[0-9A-Fa-f]{1,4}){1,7}"/>
     <!-- Double colon middle -->
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1,6}(:[0-9A-Fa-f]{1,4}){1}"/>
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1,5}(:[0-9A-Fa-f]{1,4}){1,2}"/>
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1,4}(:[0-9A-Fa-f]{1,4}){1,3}"/>
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1,3}(:[0-9A-Fa-f]{1,4}){1,4}"/>
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1,2}(:[0-9A-Fa-f]{1,4}){1,5}"/>
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1}(:[0-9A-Fa-f]{1,4}){1,6}"/>
     <!-- Double colon end -->
     <xs:pattern value="([0-9A-Fa-f]{1,4}:){1,7}:"/>
     <!-- Embedded IPv4 addresses -->
     <xs:pattern value="((:(:0{1,4}){0,3}(:(0{1,4}|[fF]{4}))?)|(0{1,4}:(:0{1,4}){0,2}(:(0{1,4}|[fF]{4}))?)|((0{1,4}:){2}(:0{1,4})?(:(0{1,4}|[fF]{4}))?)|((0{1,4}:){3}(:(0{1,4}|[fF]{4}))?)|((0{1,4}:){4}(0{1,4}|[fF]{4})?)):(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])"/>
     <!-- The unspecified address -->
     <xs:pattern value="::"/>
   </xs:restriction>
 </xs:simpleType>

Solution

  • You want a union type here:

    <xs:element name="remote_ip" type="IPv4_or_IPv6"/>
    
    <xs:simpleType name="IPv4_or_IPv6">
      <xs:union memberTypes="IPv4 IPv6"/>
    </xs:simpleType>