【问题标题】:How can I author a XML Schema that requires one attribute to be present when another is present?我如何创作一个 XML Schema,当另一个属性存在时,它需要一个属性存在?
【发布时间】:2013-11-13 18:31:47
【问题描述】:

假设我有一个这样的 XML 文件:

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book
    Title="Animal Farm"
    Author="George Orwell"
    />
</Books>

是否可以为此 XML 文件编写一个 XSD,该文件显示:如果 Book 元素具有 Title 属性,那么 Author 属性也必须存在?请注意,我不是在询问基于属性值的限制,而是基于属性名称。

【问题讨论】:

    标签: xml xsd


    【解决方案1】:

    在 XSD 1.0 中,您必须在应用程序级别施加该约束。

    在 XSD 1.1 中,您可以使用 xs:assert 来施加约束:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="Books">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Book" minOccurs="0" maxOccurs="unbounded">
              <xs:complexType>
                <xs:attribute name="Title"/>
                <xs:attribute name="Author"/>
                <xs:assert test="not(@Title) or @Author"/>
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    

    【讨论】:

    • 这也可以通过条件类型分配来完成(也许更方便),但无论哪种方式都需要 XSD 1.1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2022-10-01
    • 1970-01-01
    • 2012-04-24
    • 2021-05-31
    相关资源
    最近更新 更多