为什么我的 XSD 允许 XML 中的禁止属性?

Why is my XSD allowing a prohibited attribute in my XML?

我已将一个名为 Classroom 的属性插入到一个名为 Lecture 的元素中。这是 XML 架构:

<xsd:attribute name="Classroom" use="required">
<xsd:simpleType>
    <xsd:restriction base="xsd:string">
        <xsd:minLength value="0"/>
        <xsd:maxLength value="7"/>
    </xsd:restriction>
</xsd:simpleType>

.
.
.
<xsd:complexType name="labType"> 
        <xsd:complexContent>
            <xsd:restriction base="eventType">
                <xsd:sequence>
                    <xsd:element name="Title" type="xsd:string"/>
                    <xsd:element name="Lecture" maxOccurs="10" minOccurs="1"/>
                </xsd:sequence>
                        <xsd:attribute name="Clasroom" use="prohibited"/>
                </xsd:restriction>
        </xsd:complexContent>
    </xsd:complexType>
.
.
.
<xsd:element name="Lab" substitutionGroup="Event" type="labType"/>

我遇到的问题是此架构未对属性应用限制。 我试图验证此 XML 代码:

 <Lab>
                <Title>Artificial Intelligence</Title>
                <Lecture Classroom="BA">    
                    <Day>Friday</Day>
                    <Time>17:00-18:00</Time>
                </Lecture>                  
    </Lab>

我的问题是这个 XML 被报告为有效,即使它使用属性 "Classroom"(它不应该这样做)。 我是 XML 的新手,所以请不要苛刻。 提前致谢!

您对 Lecture

的声明
<xsd:element name="Lecture" maxOccurs="10" minOccurs="1"/>

未声明 [​​=12=] 的类型,因此您实际上允许 Lecture 上的任何内容和任何属性 ,无论您可能有任何限制在 XSD.

中的任何其他地方定义 Classroom

这是一个完整的 XSD,它将成功验证您的 XML:

<xs:schema  xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Lab">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Title" type="xs:string"/>
        <xs:element name="Lecture">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Day" type="xs:string"/>
              <xs:element name="Time" type="xs:string"/>
            </xs:sequence>
            <xs:attribute name="Classroom">
              <xs:simpleType>
                <xs:restriction base="xs:string">
                  <xs:minLength value="0"/>
                  <xs:maxLength value="7"/>
                </xs:restriction>
              </xs:simpleType>              
            </xs:attribute>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

上面的 XSD 将允许 Lecture 上的 Classroom 属性,但会将值限制为长度在 0 到 7 之间的字符串,包括在内。

您还可以添加 xs:attribute/use="prohibited" 以防止 @Classroom 出现在 Lecture 上,但是您的原始标题和问题的这一部分

The problem I'm having is that this schema does not apply the restriction on the attribute.

暗示你的问题的重点是为什么限制没有生效。也许您指的是一般意义上的 any 限制——xs:restrictionuse="prohibit"。好吧,答案是一样的:通过不为 Lecture 分配类型,您允许它是任何类型并具有任何属性。

Clasroom 中的错字(只有 1 个 's')

<xsd:attribute name="Clasroom" use="prohibited"/>

问题的另一部分是属性限制应用于 Lab 元素而不是 Lecture 元素。