使用属性值验证元素值

validate element value with attribute value

<list count="3">foo bar baz</list>

有没有办法检查 list 元素是否包含 3 个元素,如属性 count 中所说?

XSD 1.0 单独无法强制执行此约束,但 XSD 1.1 可以通过 xs:assert:

<?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="list">
    <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="count" use="required" type="xs:int"/>        
        <xs:assert test="count(tokenize(., ' ')) = @count"/>
      </xs:extension>
    </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>