Как правильно использовать unique и Keyref в XML-схеме?

У меня есть эта XML-схема, но я не знаю, как ее завершить, чтобы добиться того, что мне нужно. Я много искал в Интернете об уникальности и использовании ключевых слов, но все, что я могу найти, это основные примеры.

Это моя схема:

    <xs:element name="access" type="myaccess" />

    <xs:complexType name="myaccess">
        <xs:sequence>
            <xs:element name="user" type="myuser" minOccurs="0" maxOccurs="unbounded">
                <xs:unique name="u_idunique">
                    <xs:selector xpath="user" />
                    <xs:field xpath="@id" />
                </xs:unique>
            </xs:element>
            <xs:element name="authorization" type="myauthorization" minOccurs="0" maxOccurs="unbounded">

            <!-- HERE I WANT A KEYREF TO id attribute of user element -->
            <!-- HERE I WANT A KEYREF TO id attribute of building element OR door element -->

            </xs:element>
            <xs:element name="building" type="mybuilding" minOccurs="0" maxOccurs="unbounded" >
                <!-- I DON'T KNOW HOW TO SPECIFY THAT id of building, id of door and id of gate are in the same scope -->
                <xs:unique name="b_idunique">
                    <xs:selector xpath="building" />
                    <xs:field xpath="@id" />
                </xs:unique>
            </xs:element>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="myuser">
        <xs:attribute name="id" type="my_id" use="required" />
        <xs:attribute name="name" type="xs:string" use="required" />
        <xs:attribute name="phone" type="my_string_numeric" use="required" />
    </xs:complexType>

    <xs:complexType name="mybuilding">
        <xs:sequence>
            <xs:element name="door" type="mydoor" minOccurs="0" maxOccurs="unbounded">
                <!-- I DON'T KNOW HOW TO SPECIFY THAT id of building, id of door and id of gate are in the same scope -->
                <xs:unique name="d_idunique">
                    <xs:selector xpath="door" />
                    <xs:field xpath="@id" />
                </xs:unique>
            </xs:element>
        </xs:sequence>
        <xs:attribute name="id" type="my_id" use="required" />
        <xs:attribute name="name" type="xs:string" use="required" />
        <xs:attribute name="country" type="xs:string" use="required" />
    </xs:complexType>

    <xs:complexType name="mydoor">
        <xs:sequence>
            <xs:element name="gate" type="mygate" maxOccurs="unbounded">
                <!-- I DON'T KNOW HOW TO SPECIFY THAT id of building, id of door and id of gate are in the same scope -->
                <xs:unique name="g_idunique">
                    <xs:selector xpath="gate" />
                    <xs:field xpath="@id" />
                </xs:unique>
            </xs:element>
        </xs:sequence>
        <xs:attribute name="id" type="my_id" use="required" />
        <xs:attribute name="address" type="xs:string" use="required" />
        <xs:attribute name="status" type="mystatus" default="DISABLED" />
    </xs:complexType>

    <xs:complexType name="mygate">
        <xs:attribute name="id" type="my_id" use="required" />
        <xs:attribute name="type" type="mytype" use="required" />
        <xs:attribute name="status" type="mystatus" default="DISABLED" />
    </xs:complexType>

    <xs:complexType name="myauthorization">
        <xs:sequence>
            <xs:element name="validityperiod" type="myvalidityperiod" />
        </xs:sequence>
        <xs:attribute name="idu" type="my_id" use="required" />
        <xs:attribute name="idao" type="my_id" use="required" />
    </xs:complexType>

    <!-- OMITTED USELESS PART OF THE SCHEMA -->

</xs:schema>

У меня две проблемы:

  • Я не знаю, как указать, что поле идентификатора здания, поле идентификатора двери и поле идентификатора ворот находятся в одной и той же области видимости, и я не могу иметь 2 идентичных идентификатора (два здания не могут иметь одинаковый идентификатор но дверь и здание не могут иметь одинаковый идентификатор)
  • Я не знаю, как правильно использовать элемент keyref.
    1. Я хотел бы, чтобы поданный idu элемент авторизации был идентификатором, присутствующим в одном из пользовательских элементов (см. [*] Ниже).
    2. Я хотел бы, чтобы поле idao элемента авторизации было идентификатором, присутствующим в одном из элементов здания ИЛИ в одном из элементов двери.

[*] Я пытался написать это, но это не работает:

<xs:keyref name="useridkeyref" refer="u_idunique">
    <xs:selector xpath="authorization" />   
    <xs:field xpath="@idu" />
</xs:keyref>

Я знаю, что это не короткий вопрос, и я заранее благодарю всех за чтение. Я надеюсь, что смогу получить некоторую помощь. Спасибо!

2 ответа

Решение

Уникальные ограничения и ключи находятся в области element уровень - вам нужно поместить ограничение не внутри каждого отдельного элемента, а внутри access элемент, который является общим предком их всех.

<xs:element name="access" type="myaccess">
  <xs:key name="user_id">
    <xs:selector xpath="user" />
    <xs:field xpath="@id" />
  </xs:key>
  <xs:key name="access_id">
    <xs:selector xpath="building | building/door | building/door/gate" />
    <xs:field xpath="@id" />
  </xs:key>
  <xs:keyref name="user_ref" refer="user_id">
    <xs:selector xpath="authorization" />
    <xs:field xpath="@idu" />
  </xs:keyref>
  <xs:keyref name="access_ref" refer="access_id">
    <xs:selector xpath="authorization" />
    <xs:field xpath="@idao" />
  </xs:keyref>
</xs:element>

В моем случае мне также пришлось объявить и использовать явное пространство имен для селекторов. Используйте решение от Ian Roberts и адаптировать эти атрибуты:

<xs:schema ...
        xmlns:mc="http://mycompany.com"
...
>
...    
    <xs:selector xpath="mc:user" />      
  ...      
    <xs:selector xpath="mc:authorization" />
  ...
 </xs:element>

Смотрите также здесь /questions/8026527/xsd-unikalnoe-ogranichenie-ne-rabotaet/8026534#8026534

Другие вопросы по тегам