通过 XSD 限制具有属性的元素数量? [英] Limit number of elements with attribute via XSD?

查看:22
本文介绍了通过 XSD 限制具有属性的元素数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一段 XML

<items>
    <itemUID>uid-1</itemUID>
    <itemUID>uid-2</itemUID>
    <itemUID key="true">uid-3</itemUID>
    <itemUID>uid-4</itemUID>
    <itemUID>uid-5</itemUID>
    <itemUID key="true">uid-6</itemUID>
    <itemUID>uid-7</itemUID>
</items>

规则:元素items可以包含从1到无界元素itemUID,但只能包含0或2或3个具有属性的元素键.

Rule: Element items can contain from 1 to unbounded elements itemUID, but only 0 or 2 or 3 elements with attribute key.

我可以仅使用 XSD 限制来定义此规则吗?

Can I define this rule with XSD restrictions only?

推荐答案

您无法在 XSD 1.0 中表达您的约束,但在 XSD 1.1 中,您可以使用 xs:assert 来限制 具有 key 属性的 itemUID 元素为 0、2、3 元素,如下所示:

You cannot express your constraint in XSD 1.0, but in XSD 1.1, you can use xs:assert to limit the itemUID elements with key attributes to 0, 2, 3 elements as follows:

  <xs:assert test="count(itemUID[@key]) = (0, 2, 3)"/>

这里是完整 XSD 的上下文:

Here it is in context in a complete XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" 
  elementFormDefault="qualified" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  vc:minVersion="1.1">

  <xs:element name="items">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="itemUID" minOccurs="1" maxOccurs="unbounded">
           <xs:complexType>
             <xs:simpleContent>
               <xs:extension base="xs:string">
                 <xs:attribute name="key" type="xs:boolean">
                 </xs:attribute>
               </xs:extension>
             </xs:simpleContent>
           </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:assert test="count(itemUID[@key]) = (0, 2, 3)"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

这篇关于通过 XSD 限制具有属性的元素数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆