2014-02-28 37 views
1

我希望创建一个XML文档,其中的一个元素必须使用两个已知属性之一来定义,但不能同时使用这两个属性。XSD:A <xs:choice>等同于属性

例如,我想定义一个“webAddress”元素如下:

<xs:element name="webAddress"> 
    <xs:complexType> 
     <xs:attribute name="hostName" type="xs:string"/> 
     <xs:attribute name="hostAddress" type="xs:string"/> 
    </xs:complexType> 
</xs:element> 

但我只希望用户能够定义一个主机名的属性(例如,主机名=“)或一个hostAddress(例如,hostAddress =“”)属性,但不能同时存在,看起来该构造完成了这个元素,是否有属性的功能等价物,或者是否有更好的方法来处理这个属性?

如果找到我们不能使用W3C XML Schema来做到这一点 我们可以使用嵌入式schematron规则,但是我们可以在选择元素上做到这一点通过检查元素和属性在一起? 例如是这样的:

<xs:choice> 
    <xs:element name="webAddress"> 
     <xs:complexType> 
      <xs:attribute name="hostName" type="xs:string"/> 
     </xs:complexType> 
    </xs:element> 
    <xs:element name="webAddress"> 
     <xs:complexType> 
      <xs:attribute name="hostAddress" type="xs:string"/> 
     </xs:complexType> 
    </xs:element> 
    </xs:choice> 
+0

进一步你可以使属性为强制使用=“required” – Naren

+0

这不完全是我想看到的。 'hostName'和'hostAddress'应该具有相同的权利 – Nick

+0

相同的权利意味着? – Naren

回答

1

你可以使用“类型”替代,例如

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> 
    <!-- Some abstract type - it might define some common parts too. It is abstract and cannot be used directly for instance --> 
    <xs:complexType name="abstractType" abstract="true"/> 

    <!-- First "children" type of abstract type--> 
    <xs:complexType name="hostNameType"> 
     <xs:complexContent> 
      <!-- it is derived from abstractType and adds attribute hostName --> 
      <xs:extension base="abstractType"> 
       <xs:attribute name="hostName" type="xs:string" use="required" /> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 

    <!-- Second "children" type of abstract type --> 
    <xs:complexType name="hostAddressType"> 
     <xs:complexContent> 
      <!-- it is also derived from abstractType and adds attribute hostAddress --> 
      <xs:extension base="abstractType"> 
       <xs:attribute name="hostAddress" type="xs:string" use="required" /> 
      </xs:extension> 
     </xs:complexContent> 
    </xs:complexType> 

    <!-- Element of abstractType --> 
    <xs:element name="webAddress" type="abstractType" /> 

</xs:schema> 

在实例文档中,你必须指定其实际使用类型:

<?xml version="1.0" encoding="UTF-8"?> 
<!-- by xsi:type you defined which "concrete" type is really used --> 
<webAddress xsi:type="hostNameType" hostName="String" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> 

<?xml version="1.0" encoding="UTF-8"?> 
<webAddress xsi:type="hostAddressType" hostAddress="xxxx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> 

但定义是一个有点冗长,而且不是很明显的第一眼看什么类型的“网络地址”真的可以。但它可能是你的一种方式。

+0

谢谢,我认为这是我们能做的最好的。 – Nick

0

使用断言或条件类型赋值很容易在XSD 1.1中实现所需内容,但在XSD 1.0中无法实现。

XSD 1.1目前由Saxon,Xerces和Altova支持。