XML Schema:如何声明具有相同名称的属性或子元素的complexType

3

使用我的XSD模式,我希望元素具有必需的附加值,可以在元素的属性或其子元素中指定。

例如:应允许以下元素:

<flower color="red" />

或者:

<flower><color>red</color></flower>

但以下元素不应该是有效的:

<flower />

并且:

<flower></flower>

并且:

<flower color="red"><color>blue</color></flower>

我完全不知道如何实现这个。

2个回答

3
在XSD 1.0中,您唯一的选择是使用散文来记录限制条件。(例如,在模式架构中对元素声明有类似限制的情况下所做的方式。)
在XSD 1.1中,您可以使用断言来记录和执行该约束。稍微修改Petru Gardea建议的模式文档,我们可以得到:
<xs:schema targetNamespace="http://example.com/colors" 
       xmlns:tns="http://example.com/colors" 
       elementFormDefault="qualified" 
       xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="flowerColor">
    <xs:restriction base="xs:normalizedString">
      <xs:minLength value="1"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:complexType name="flowerVariantC">
    <xs:sequence>
      <xs:element name="color" 
                  type="tns:flowerColor" 
                  minOccurs="0"/>
    </xs:sequence>  
    <xs:attribute name="color" 
                  type="tns:flowerColor" 
                  use="optional"/>
    <xs:assert test="(./tns:color or ./@color)
        and not(./tns:color and ./@color)"/>
  </xs:complexType>

  <xs:element name="flower" type="tns:flowerVariantC"/>    
  <xs:element name="test"/>

</xs:schema>

给定刚刚展示的模式文档和以下实例,Saxon 拒绝将第一个和第四个 flower 元素视为无效。
<test xmlns="http://example.com/colors"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://example.com/colors colors.xsd">
  <flower/>
  <flower color="red"/>
  <flower><color>blue</color></flower>
  <flower color="blue"><color>blue</color></flower>
</test>

话虽如此,我的直觉是建议不要选择这种设计,因为它过于复杂:选择将颜色作为属性,或选择将其作为子元素。每种设计都可行,并不意味着在文档中允许其变化是一个可行的设计。


1
假设使用XSD 1.0,下面的示例是一个起点:
<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd" xmlns="http://tempuri.org/XMLSchema.xsd" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:simpleType name="flowerColor">
        <xsd:restriction base="xsd:normalizedString">
            <xsd:minLength value="1"/>
        </xsd:restriction>
    </xsd:simpleType>

    <xsd:complexType name="flowerVariantA">
        <xsd:attribute name="color" type="flowerColor" use="required"/>
    </xsd:complexType>

    <xsd:complexType name="flowerVariantB">
        <xsd:sequence>
            <xsd:element name="color" type="flowerColor"/>
        </xsd:sequence>
    </xsd:complexType>

    <xsd:element name="flower" type="flowerVariantA"/>
</xsd:schema>

VariantA和B是互斥的,并匹配您的示例XML之一。如果您的意图是同时允许两者,则XSD 1.0不允许混合属性和元素的内容“选择”。

此外,您无法控制XML元素的自关闭;这意味着使用VariantA,以下内容是有效的:

<flower color="red"></flower>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接