如何根据元素的属性值限制元素的值

How to restrict the values of an element according to the value of its attribute

在我的大学作业项目中,我需要编写一个 XSD(XML Schema) 来描述学校历史将包含哪些元素。在其中一种情况下,我有元素 "Disciplina",它有一个属性 "categoria"(示例如下):

<Disciplina categoria = "atividade academica">
  (...other elements here...)
  <situacao>AC</situacao>
</Disciplina>

除此之外,元素"situacao"在一些特定的字符串值上有一个范围:"AP,RM,RF,ED,AB,AE,AI,TR,TD,RI,IN"和"categoria"是相同的逻辑:"obrigatoria,optativa,livre escolha,atividade academica."

但是,当 "categoria" 为 "atividade academica" 时,我想将元素 "situacao" 的可能值限制为 "AC" 或 "NC",否则,限制值将为 "AP"、"RM"、"RF"、"ED"、"AB"、"AE"、"AI"、"TR"、"TD"、"RI"、"IN"。下面的 xml 表达了我试图表达的高层次思想:

<element>
  <name>situacao</name>
  <type>String</type>
  <range>AP,RM,RF,RF,ED,AB,AE,AI,TR,TD,RI,IN</range>
  <range categoria = "atividade academica">AC,NC</range>
</element>

我的问题是:如何根据 "categoria" 值,在 XML 模式中表示 "situacao" 值限制的这种变化?

这不能在 XSD 1.0 中完成(这是许多 XSD 处理器支持的版本,例如来自 Microsoft 的处理器)。在 XSD 1.1(由 Xerces、Saxon 和 Altova 支持)中,可以通过几种方式完成:

(a) 通用断言,例如

<xs:assert test="(@categoria = 'atividade academia' and situacio = ('AC', 'NC')) 
  or (@categoria = 'xxxx' and situacio = ('ED', 'AB'))...."/>

(b) 条件类型赋值,使用xs:alternative:这里的想法是将元素的类型定义为其属性值的函数;同样,这是使用 XPath 表达式完成的。