【问题标题】:XSD for same tag different attribute names相同标签不同属性名称的 XSD
【发布时间】:2015-05-07 17:35:50
【问题描述】:

我有一个奇怪的 xml 场景,想用 xsd 验证它。 下面是xml

<tag1>
   <tag2 attribute1="value1" />
   <tag2 attribute2="value2" />
<tag1>

下面是我正在使用的xsd

<xs:element name="tag1">
  <xs:complexType>
    <xs:sequence>
      <xs:element minOccurs="1" maxOccurs="unbounded" name="tag2">
        <xs:complexType>
          <xs:attribute name="attribute1" type="xs:string" use="optional" />
          <xs:attribute name="attribute2" type="xs:string" use="optional" />
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

如果tag2 具有attribute1 或attribute2 两者或其中任何一个,则一切正常。 但我的情况是,如果没有如下属性 1 的 tag2

<tag1>
   <tag2 attribute2="value2" />
<tag1>

然而它应该被认为是无效的

<tag1>
   <tag2 attribute1="valueX" />
<tag1>

有效。

有什么方法可以构建 XSD 来验证这种情况吗?

【问题讨论】:

  • 多年前,你问过this question - 并且已经提出了几个答案。请accept one of them or otherwise react to them.
  • 同意@MathiasMüller 的观点,即您应该接受/对过去的答案做出反应,并且这个问题有点不清楚。如果每个tag2 都必须有一个attribute1,那么请参阅Mathias' answer。如果您说必须至少存在一个具有attribute1tag2,那么您将需要XSD 1.1 来表达这样的约束。让我们知道 XSD 1.1 是否适合您。
  • 不能使用 XSD 1.1 :( 所以我想我必须通过代码来验证它

标签: xml xsd


【解决方案1】:

我不确定我是否理解,但为什么不简单地声明使用attribute1 是必需的,而不是可选的?

 <xs:element minOccurs="1" maxOccurs="unbounded" name="tag2">
    <xs:complexType>
      <xs:attribute name="attribute1" type="xs:string" use="required" />
      <xs:attribute name="attribute2" type="xs:string" use="optional" />
    </xs:complexType>
 </xs:element>

那么,没有attribute1 属性的tag2 元素将被视为无效。

【讨论】:

  • 这不能完成,因为它暗示 tag2 应该始终包含属性 1,但它不需要。您的解决方案非常适合以下场景 但您看到第二个 tag2 不需要(或不应该) 有属性1
【解决方案2】:

我不确切知道您要强加什么规则,但 XSD 1.0 中的一般规则是,如果两个同级元素具有相同的名称,那么它们必须具有相同的类型(即,您不能应用不同的验证规则到两个同名的兄弟元素)。

当然,在 XSD 1.1 中,您可以使用断言来解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多