如何为根元素定义必需的属性?

How can I define required attributes for the root element?

我找不到如何为我的元素添加必需的属性 shop-offer。我尝试放置

<xs:attribute name="id" type="xs:integer" use="required"/>

在架构根以及元素的 <xs:complexType> 中,但它不起作用。我总是收到这里不允许的错误。

那我该怎么做呢?

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="shop-offer">

    <xs:complexType mixed="true">

      <xs:sequence>
        <xs:choice maxOccurs="unbounded">
          <xs:element name="tool">
            <xs:complexType>
              <xs:attribute name="id" type="xs:integer" use="required"/>      
            </xs:complexType>       
          </xs:element>     
          <xs:element name="widget">
            <xs:complexType>
              <xs:attribute name="id" type="xs:integer" use="required"/>      
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:sequence>
    </xs:complexType>

  </xs:element>
</xs:schema>

您的 xs:attribute 声明没问题,但它们的放置要求在 toolwidget 元素上存在 id 属性。

如果您还希望 shop-offer 根元素上需要 id,则必须在 xs:complexType 内(xs:sequence 之后)放置另一个对于 shop-offer:

这个XSD,

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="shop-offer">
    <xs:complexType mixed="true">
      <xs:sequence>
        <xs:choice maxOccurs="unbounded">
          <xs:element name="tool">
            <xs:complexType>
              <xs:attribute name="id" type="xs:integer" use="required"/> 
            </xs:complexType>                           
          </xs:element>                   
          <xs:element name="widget">
            <xs:complexType>
              <xs:attribute name="id" type="xs:integer" use="required"/> 
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:sequence>

      <!--  This @id is for the shop-offer root element -->
      <xs:attribute name="id" type="xs:integer" use="required"/> 

    </xs:complexType>
  </xs:element>
</xs:schema>

将成功验证此 XML,

<shop-offer id="1">
  <tool id="2"/>
</shop-offer>

根据要求。


注意:你确定要mixed="true"吗,这会让这个XML有效,

<shop-offer id="1">
  Text here.
  <tool id="2"/>
  And more text here.
</shop-offer>

可能不尽如人意。