XSD elements with same name but different types

时间:2015-10-29 15:43:22

标签: xml xsd xml-validation

I need to write a XSD which will validate the attribute as well as the value of the element. So far I am able to validate the attributes but not the value. Thanks for your help in advance.

My XML:

<params>
    <param dataType="java.lang.String">12A</param>
    <param dataType="java.lang.Integer">6455</param>
    <param dataType="oracle.jbo.domain.Date">2014-10-01</param>
    <param dataType="oracle.jbo.domain.Date">2018-10-01</param>
    <param dataType="java.lang.String">H1</param>
    <param dataType="java.lang.String">4235AS</param>
    <param dataType="java.lang.String">5aZ</param>
    <param dataType="java.lang.String">q2w</param>
    <param dataType="java.lang.Integer">10</param>
    <param dataType="java.lang.Integer">3</param>
</params>

My XSD

<?xml version="1.0"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="params">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="10" 
                    name="param" type="paramType" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="paramType">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="dataType" type="validAttributeType" use="optional" />
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

  <xs:simpleType name="validAttributeType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="java.lang.String" />
      <xs:enumeration value="java.lang.Integer" />
      <xs:enumeration value="oracle.jbo.domain.Date" />

    </xs:restriction>
  </xs:simpleType>
</xs:schema>

So my need is, if the dataType says Integer it should only accept numbers as value or if it says date, then the value should be date not anything else.

1 个答案:

答案 0 :(得分:0)

XSD 1.0

无法在XSD 1.0中完成基于属性值的类型检查。

XSD 1.1

您可以使用 Condition Type Assignment

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           vc:minVersion="1.1">

  <xs:element name="params">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="10" name="param">
          <xs:alternative test="@dataType='java.lang.String'" type="xs:string"/> 
          <xs:alternative test="@dataType='java.lang.Integer'" type="xs:integer"/> 
          <xs:alternative test="@dataType='oracle.jbo.domain.Date'" type="xs:date"/> 
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

虽然这是表示基于属性的类型的正确结构,但您应注意在某些情况下XSD类型可能与Java类型不同,因此请检查以确保根据您的要求可以容忍任何差异。