我可以在没有父元素的情况下在xsd中创建一个类型吗?

时间:2015-07-07 14:27:32

标签: xml xsd xml-parsing xsd-validation choice

我在.xsdIPIPv6中定义了两种类型。我需要在.xml文件中有一个元素,以便它是这两种类型中的任何一种。

要做到这一点,我想我可能会使用xsd:choice,但问题是它暗示了一个父元素,例如:

<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>

这允许我在.xml

中进行以下操作
<remote_ip>
  <remote_ip>10.0.0.1</remote_ip>
</remote_ip>

我需要以下内容:

<remote_ip>10.0.0.1</remote_ip>

IPIPv6类型定义:

<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>

1 个答案:

答案 0 :(得分:2)

你想要一个联合类型:

<xs:element name="remote_ip" type="IPv4_or_IPv6"/>

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