34.2. 由 Restriction 定义的简单类型
概述
XML 架构允许您通过从其他原语类型或简单类型分离新类型来创建简单类型。简单类型通过 simpleType
元素进行描述。
新的类型通过限制一个或多个方面 的基本类型 来加以描述。这些限制会限制可以在新类型中保存的可能有效的值。例如,您可以定义一个简单类型 SSN
,它是仅包含 9 个字符的字符串。
每个原语 XML 架构类型都有其自己的一组可选面。
流程
要定义您自己的简单类型,请执行以下操作:
- 确定新简单类型的基本类型。
- 根据所选基本类型的可用数据数据,确定定义新类型的限制。
-
使用本节中显示的语法,将适当的
simpleType
元素输入到合同的 type 部分。
在 XML 架构中定义简单类型
例 34.1 “简单类型语法” 显示描述简单类型的语法。
例 34.1. 简单类型语法
<simpleType name="typeName"> <restriction base="baseType"> <facet value="value" /> <facet value="value" /> ... </restriction> </simpleType>
类型描述包含在 simpleType
元素中,由 name
属性的值来标识。定义新简单类型的基本类型由 xsd:restriction
元素 的基本
属性指定。每个 facet 元素都在 限制
元素内指定。可用的难题及其有效设置取决于基本类型。例如,xsd:string
有很多问题,其中包括:
-
length
-
minLength
-
maxLength
-
pattern
-
whitespace
例 34.2 “后代码简单类型” 显示一个简单的类型定义,它代表了用于美国状态的双字母后期代码。它只能包含两个大写字母。TX
是有效值,但 tx
或 tX
不是有效的值。
例 34.2. 后代码简单类型
<xsd:simpleType name="postalCode"> <xsd:restriction base="xsd:string"> <xsd:pattern value="[A-Z]{2}" /> </xsd:restriction> </xsd:simpleType>
映射到 Java
Apache CXF 将用户定义的简单类型映射到简单类型的基本类型的 Java 类型。因此,任何使用简单类型 postalCode
的消息(在 例 34.2 “后代码简单类型” 中)映射到一个 字符串
,因为 postalCode
的基本类型是 xsd:string
。例如,例 34.3 “使用简单类型进行贡献请求” 中显示的 WSDL 片段生成 Java 方法 state()
,其使用参数 postalCode
( String
)。
例 34.3. 使用简单类型进行贡献请求
<message name="stateRequest"> <part name="postalCode" type="postalCode" /> </message> ... <portType name="postalSupport"> <operation name="state"> <input message="tns:stateRequest" name="stateRec" /> <output message="tns:stateResponse" name="credResp" /> </operation> </portType>
Enforcing facets
默认情况下,Apache CXF 不强制实施任何用于限制简单类型的问题。但是,您可以通过启用 schema 验证来配置 Apache CXF 端点来强制面临的问题。
要将 Apache CXF 端点配置为使用 schema 验证,将 schema-validation-enabled
属性设为 true
。例 34.4 “Service Provider Configured to Use Schema Validation” 显示使用 schema 验证的服务提供商的配置
例 34.4. Service Provider Configured to Use Schema Validation
<jaxws:endpoint name="{http://apache.org/hello_world_soap_http}SoapPort"
wsdlLocation="wsdl/hello_world.wsdl"
createdFromAPI="true">
<jaxws:properties>
<entry key="schema-validation-enabled" value="BOTH" />
</jaxws:properties>
</jaxws:endpoint>
有关配置模式验证的详情,请参考 第 24.3.4.7 节 “架构验证类型值”。