断言包含 XSD

Assertion contains for XSD

我想用 XSD 为 XML 创建条件验证。我想如果元素单位是 "uri" 那么元素值必须包含 "http",否则如果元素单位是 "date" 那么元素值必须是时间戳,等等......我我从使用 xs:assert 的简单验证开始,但无法正常工作。我已经测试了 xs:assertion 但它产生了同样的错误。

xmllint --noout --schema metadata.xsd metadata.xml 
metadata.xsd:46: element assert: Schemas parser error : Element '{http://www.w3.org/2001/XMLSchema}complexType': The content is not valid. Expected is (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))).
WXS schema metadata.xsd failed to compile

.

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="metadata">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="AVU" minOccurs="0" maxOccurs="unbounded">
     <xs:complexType>
      <xs:sequence>

       <xs:element name="Target" minOccurs="0">
        <xs:simpleType>
         <xs:restriction base="xs:string">
          <xs:maxLength value="1088"/>
         </xs:restriction>
        </xs:simpleType>
       </xs:element>

       <xs:element name="Attribute">
        <xs:simpleType>
         <xs:restriction base="xs:string">
          <xs:minLength value="1"/>
          <xs:maxLength value="2700"/>
         </xs:restriction>
        </xs:simpleType>
       </xs:element>

       <xs:element name="Value">
        <xs:simpleType>
         <xs:restriction base="xs:string">
          <xs:pattern value="http://.*"/>
          <xs:maxLength value="2700"/>
         </xs:restriction>
        </xs:simpleType>
       </xs:element>

       <xs:element name="Unit">
        <xs:simpleType>
         <xs:restriction base="xs:string">
          <xs:pattern value="uri|string|integer|date|float"/>
          <xs:maxLength value="250"/>
         </xs:restriction>
        </xs:simpleType>
       </xs:element>

      </xs:sequence>
      <xs:assert test="Unit = 'uri'" />
     </xs:complexType>
    </xs:element>
   </xs:sequence>
  </xs:complexType>
 </xs:element>
</xs:schema>

xs:assert 和 xs:assertion 需要 XSD 1.1 处理器。但是您使用的是 XSD 1.0 处理器的 xmllint。

正如@potame 和@MichaelKay 已经说过的,您的错误是由于在 xs:assert 需要 XSD 1.1 处理器时使用 xs:assert 和 XSD 1.0 处理器。

您有几个选择:

  1. 接受不太严格的验证。
  2. 在 XSD 之外验证。
  3. 切换到 XSD 1.1 处理器。
  4. 重新设计您的 XML.

关于#4,您的 XML 现在非常抽象。如果您要转向更具体的元素命名,XSD 1.0 可以为您做更多的类型检查。例如,当 Unituri 时,不需要对 Value 元素进行特殊检查的 Unit 元素,您可以简单地使用 URI 类型的元素 xsd:anyURI。 (事实上​​ ,您可能更具体 name URI what is 而不是 type;例如:HomepagePaymentAPIEndpoint.)