2012-12-19 66 views
10

我在我的公司创建了一个新的dataexchange服务。我们想扩展在我们的core.xsd定义文件中定义的现有对象。这里是我需要做的一个例子:如何重写父/扩展元素内部的Xsd元素

<xs:complexType name="parentType"> 
    <xs:sequence> 
    <xs:element name="departmentName" type="core:DEPARTMENT_NAME" 
       minOccurs="0" maxOccurs="1" />  
    </xs:sequence> 
</xs:complexType> 

<xs:complexType name="childType"> 
    <xs:complexContent> 
    <xs:extension base="parentType"> 
     <xs:sequence> 
     <xs:element name="departmentName" 
        type="core:DEPARTMENT_NAME" 
        minOccurs="1" maxOccurs="1"/> 
     </xs:sequence> 
    </xs:extension> 
    </xs:complexContent> 
</xs:complexType> 

我认为这很有道理。我想覆盖父元素并使其成为必需元素。但是,一个有效的XML文件就是这样。现在哪里有一个额外的部门名称!?

<childType> 
    <departmentName>HR</departmentName> 
    <departmentName>IT</departmentName> 
</childType> 

我怎么能做到这一点,这样的XML文件将成为:

<childType> 
    <departmentName>IT</departmentName> 
</childType> 

谢谢, 克雷格

回答

7

您需要使用的限制,而不是延伸。这将是您指定场景的完整有效模式(我已经宽松地使用名称空间来使其有效)。

<?xml version="1.0" encoding="utf-8" ?> 
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) --> 
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" xmlns:core="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:complexType name="parentType"> 
     <xs:sequence> 
      <xs:element name="departmentName" type="core:DEPARTMENT_NAME" minOccurs="0"/> 
     </xs:sequence> 
    </xs:complexType> 

    <xs:complexType name="childType"> 
     <xs:complexContent> 
      <xs:restriction base="parentType"> 
       <xs:sequence> 
        <xs:element name="departmentName" type="core:DEPARTMENT_NAME"/> 
       </xs:sequence> 
      </xs:restriction> 
     </xs:complexContent> 
    </xs:complexType> 

    <xs:simpleType name="DEPARTMENT_NAME"> 
     <xs:restriction base="xs:string"/> 
    </xs:simpleType> 

    <xs:element name="childType" type="childType"/> 
</xs:schema> 
+0

感谢Petru,那就是我一直在寻找的东西。问题虽然:如果我仍然想扩展parentType会发生什么?假设我想为扩展它的类型添加一些缺失的字段。我注意到你只能限制或扩展,但不能同时为父类型。我会尝试,但是是否需要创建一个扩展childType的grandChild类型,该类型对parentType有限制?这似乎过于冗长和繁琐,是不是一个更清洁的解决方案? – Craig

+1

为了构建childType的顶部,您必须创建grandchildType。我同意这看起来很麻烦 - 尤其是维护xsd:限制......但这就是XSD 1.0。至于“更清洁”的限定词...它真的在细节中,而且是旁观者的眼睛。如果这是一个新的设计,我相信有不同的方式来布局你的层次结构,以便它给你合理的东西......你还必须考虑XSD的代码绑定... –