【问题标题】:How can I specify an element to have an attribute that states how many children it contains in an XML Schema?如何指定一个元素以具有一个属性,该属性说明它在 XML 模式中包含多少个子元素?
【发布时间】:2011-09-18 05:49:16
【问题描述】:

有可能吗?

  • 我知道可以根据正则表达式进行限制,但不是这样
  • 我知道可以将属性声明为由 XPath 计算的外键,但它似乎必须是唯一的

示例:

<root children="2">
    <child />
    <child />
</root>

【问题讨论】:

    标签: xml xpath xsd schema xsd-validation


    【解决方案1】:

    XSD 1.1 允许您表达这种约束:

    <xs:element name="root">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="child" maxOccurs="unbounded"/>
        </xs:sequence>
        <xs:attribute name="children" type="xs:integer"/>
      </xs:complexType>
      <xs:assert test="@children = count(child)"/>
    </xs:element>
    

    XSD 1.1 目前在 Saxon 和 Xerces 中实现。

    【讨论】:

      【解决方案2】:

      W3C Schema 1.0 无法根据实例文档限制属性值。

      Schematron 是用于验证文档是否符合此类自定义验证方案的出色工具。

      例如:

      <?xml version="1.0" encoding="UTF-8"?>
      <schema xmlns="http://purl.oclc.org/dsdl/schematron">
          <pattern>
              <rule context="root[@children]">
                  <assert 
                      id="children-value" 
                      test="@children=count(child)" 
                      flag="error">
                      The root/@children value must be equal to the number of child elements.
                      </assert>
                  </rule>
          </pattern>
      </schema>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-30
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多