Технология XSD
1/38

Технология XSD

1. Технология XSD

Обзор
www.epam.com
www.epam.com
EPAM
EPAM Systems
Systems
1

2. Что такое XML схема (XSD)?

• XML Schema definition language (XSD) в настоящее время
стандартный язык схем для XML документов и данных.
• 2 мая 2001, World Wide Web Consortium (W3C) опубликовал
версию 1.0 стандарта XSD.
• XML Schema описывает элементы XML документа
• Описывает атрибуты в XML
• Описывает дочерние элементы их порядок и количество
• Описывает типы данных для элементов и атрибутов
www.epam.com
EPAM Systems
2

3. Зачем нужны схемы?

Server-side programmer
Client-side
programmers
www.epam.com
EPAM Systems

4. Создание XML Схемы

<?xml
<?xml version="1.0"?>
version="1.0"?>
<xs:schema
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.epam.com"
targetNamespace="http://www.epam.com"
xmlns="http://www.epam.com"
xmlns="http://www.epam.com"
elementFormDefault="qualified">
elementFormDefault="qualified">
...
...
</xs:schema>
</xs:schema>
• Элемент <schema> - корневой элемент любой XML схемы
• xmlns:xs="http://www.w3.org/2001/XMLSchema" - Объявление
пространства имен XML схемы c префиксом xs
• targetNamespace="http://www.epam.com" – для этого пространства
имен применяется схема
• xmlns="http://www.epam.com" – пространство имен по умолчанию
(без префикса)
• elementFormDefault="qualified" - все элементы должны быть
namespace qualified
www.epam.com
EPAM Systems
4

5. Простые элементы

• Элементы объявляются с использованием элемента <element>.
• Простой элемент может содержать только текст.
• Простой элемент не может содержать атрибутов.
• Объявляется простым типом (базовым типом или новым типом с расширением
или ограничением базового типа c помощью элемента simpleType).
<xs:element
<xs:element name="age"
name="age" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="age">
name="age">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:integer">
base="xs:integer">
<xs:minInclusive
<xs:minInclusive value="0"/>
value="0"/>
<xs:maxInclusive
<xs:maxInclusive value="100"/>
value="100"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
5

6. Объявление атрибутов

• Атрибуты объявляются с использованием элемента
<attribute>
• Атрибут всегда объявляется простым типом
<xs:attribute
<xs:attribute name="lang"
name="lang" type="xs:string"/>
type="xs:string"/>
<lastname
<lastname lang="EN">Smith</lastname>
lang="EN">Smith</lastname>
• Для атрибута можно определить значение по умолчанию
или фиксированное значение
<xs:attribute
<xs:attribute name="lang"
name="lang" type="xs:string"
type="xs:string" default="EN"/>
default="EN"/>
<xs:attribute
<xs:attribute name="lang"
name="lang" type="xs:string"
type="xs:string" fixed="EN"/>
fixed="EN"/>
www.epam.com
EPAM Systems
6

7. Простой тип (Simple Type)


Элемент simpleType определяет простой тип элементов или атрибутов,
накладывая ограничения или расширения на базовые типы
Может быть именованным или анонимным внутри элемента (атрибута)
<xs:element
<xs:element name="age"
name="age" type="ageType"/>
type="ageType"/>
<xs:simpleType
<xs:simpleType name="ageType">
name="ageType">
<xs:restriction
<xs:restriction base="xs:integer">
base="xs:integer">
<xs:minInclusive
<xs:minInclusive value="0"/>
value="0"/>
<xs:maxInclusive
<xs:maxInclusive value="100"/>
value="100"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
Описан элемент "age" который может иметь числовые значения от 0 до
100 включительно
<age>101</age>
<age>101</age>
www.epam.com
Не валидный
элемент
EPAM Systems
7

8. Составной тип (Complex Type)

• Составной тип описывает элементы, содержащего другие элементы и/или
атрибуты
• Составной тип описывается с помощью элемента complexType
• Может быть именованным или анонимным внутри элемента
<xs:element
<xs:element name="note">
name="note">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="to"
name="to" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="from"
name="from" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="heading"
name="heading" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="body"
name="body" type="xs:string"/>
type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
8

9. Элемент simpleContent


Для расширения/ограничения составного типа, который может
содержать только текст как содержимое, используется элемент
simpleContent
Используется для добавления атрибутов
<xsd:element
<xsd:element name="shoesize">
name="shoesize">
<xsd:complexType>
<xsd:complexType>
<xsd:simpleContent>
<xsd:simpleContent>
<xsd:extension
<xsd:extension base="xsd:integer">
base="xsd:integer">
<xsd:attribute
<xsd:attribute name="country"
name="country" type="xsd:string"/>
type="xsd:string"/>
</xsd:extension>
</xsd:extension>
</xsd:simpleContent>
</xsd:simpleContent>
</xsd:complexType>
</xsd:complexType>
</xsd:element>
</xsd:element>
www.epam.com
EPAM Systems
9

10. Элемент complexContent


Элемент complexContent служит для расширения или ограничения
составных типов, объявленных ранее
<xs:complexType
<xs:complexType name="personinfo">
name="personinfo">
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="firstname"
name="firstname" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="lastname"
name="lastname" type="xs:string"/>
type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
<xs:complexType
<xs:complexType name="fullpersoninfo">
name="fullpersoninfo">
<xs:complexContent>
<xs:complexContent>
<xs:extension
<xs:extension base="personinfo">
base="personinfo">
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="address"
name="address" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="city"
name="city" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="country"
name="country" type="xs:string"/>
type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:extension>
</xs:extension>
</xs:complexContent>
</xs:complexContent>
</xs:complexType>
</xs:complexType>
www.epam.com
EPAM Systems
10

11. Объявление типов

• Типы для элементов /атрибутов могут быть
• Локальными и анонимными (в теле элемента element)
• Глобальными и именованными (непосредственно в элементе
schema)
<xs:simpleType
name="newType">
•<xs:simpleType
У именованныхname="newType">
объявлений определяется атрибут name
<xs:restriction
<xs:restriction base="xs:integer">
base="xs:integer">
<xs:minInclusive
<xs:minInclusive value="0"/>
value="0"/>
<xs:maxInclusive
<xs:maxInclusive value="100"/>
value="100"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
<xs:complexType
<xs:complexType name="compType">
name="compType">
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="to"
name="to" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="from"
name="from" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="heading"
name="heading" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="body"
name="body" type="xs:string"/>
type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
<xs:element
<xs:element name="age"
name="age" type="newType"/>
type="newType"/>
<xs:element
<xs:element name="note"
name="note" type="compType"/>
type="compType"/>
www.epam.com
EPAM Systems
11

12. Использование элементов и атрибутов


На именованные объявления элементов и атрибутов можно ссылаться
с помощью атрибута ref
<xs:attribute
<xs:attribute name="blue"/>
name="blue"/>
<xs:complexType
<xs:complexType name="eyeColorType">
name="eyeColorType">
<xs:attribute
<xs:attribute ref="blue"/>
ref="blue"/>
<xs:attribute
<xs:attribute name="light"/>
name="light"/>
</xs:complexType>
</xs:complexType>
<xs:element
<xs:element name="eyeColor"
name="eyeColor" type="eyeColorType"/>
type="eyeColorType"/>
<xs:element
<xs:element name="Catalog">
name="Catalog">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element ref="eyeColor"/>
ref="eyeColor"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
12

13. Базовые типы

XML schema содержит 44 базовых типа, общие из которых:
• string
• decimal
• integer
• boolean
• date
• time
www.epam.com
EPAM Systems
13

14. Ограничения (Restrictions)

Ограничения предназначены для контроля возможных значений элементов и
атрибутов XML.
Элемент
ограничения
enumeration
fractionDigits
Определяет одно из возможных значений
Задает количество знаков после запятой (>=0)
length
Задает количество символов (>=0)
maxExclusive
maxInclusive
Определяет максимальное числовое значение.
Определяет максимальное числовое значение включительно.
maxLength
Задает максимальное количество символов (>=0)
minExclusive
minInclusive
Определяет меньшее числовое значение.
Определяет меньшее числовое значение включительно.
minLength
Задает минимальное количество символов.
pattern
totalDigits
Определяет порядок и набор возможных символов
Показывает количество цифр
whiteSpace
Определяет работу с white spaces (line feeds, tabs, spaces и carriage returns)
www.epam.com
Описание
EPAM Systems
14

15. Ограничения на значения

<xs:element
<xs:element name="age">
name="age">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:integer">
base="xs:integer">
<xs:minInclusive
<xs:minInclusive value="0"/>
value="0"/>
<xs:maxInclusive
<xs:maxInclusive value="100"/>
value="100"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
<xs:element
<xs:element name="car">
name="car">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:string">
base="xs:string">
<xs:enumeration
<xs:enumeration value="Audi"/>
value="Audi"/>
<xs:enumeration
<xs:enumeration value="Golf"/>
value="Golf"/>
<xs:enumeration
<xs:enumeration value="BMW"/>
value="BMW"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
www.epam.com
 Ограничение на
значение
Ограничение
списком возможных
значений
EPAM Systems
15

16. Ограничение с помощью шаблона

<xs:element
<xs:element name="letter">
name="letter">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:string">
base="xs:string">
<xs:pattern
<xs:pattern value="[a-z]"/>
value="[a-z]"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
Ограничение в один
символ нижнего
регистра от “a” до “z”
<xs:element
<xs:element name="initials">
name="initials">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:string">
base="xs:string">
<xs:pattern
<xs:pattern value="[A-Z][A-Z][A-Z]"/>
value="[A-Z][A-Z][A-Z]"/>
</xs:restriction>
</xs:restriction>
Ограничение тремя
</xs:simpleType>
</xs:simpleType>
символами верхнего
</xs:element>
</xs:element>
регистра от “a” до “z”
www.epam.com
EPAM Systems
16

17. Ограничение с помощью шаблона

<xs:pattern
<xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
Три символа любого
регистра от “a” до “z”
<xs:pattern
<xs:pattern value="[xyz]"/>
value="[xyz]"/>
Один символ из трех
возможных (x, y или z)
<xs:restriction
<xs:restriction base="xs:integer">
base="xs:integer">
<xs:pattern
<xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>
value="[0-9][0-9][0-9][0-9][0-9]"/>
</xs:restriction>
</xs:restriction>
Пять цифр
<xs:pattern
<xs:pattern value="([a-z])*"/>
value="([a-z])*"/>
www.epam.com
Любое количество
символов нижнего
регистра от “a” до “z”
EPAM Systems
17

18. Ограничение с помощью шаблона

<xs:pattern
<xs:pattern value="([a-z][A-Z])+"/>
value="([a-z][A-Z])+"/>
<xs:pattern
<xs:pattern value="male|female"/>
value="male|female"/>
<xs:pattern
<xs:pattern value="[a-zA-Z0-9]{8}"/>
value="[a-zA-Z0-9]{8}"/>
www.epam.com
Несколько пар
чередующихся
регистрами символов
Два возможных
варианта значения
Ровно восемь букв или
цифр
EPAM Systems
18

19. Ограничение на длину

<xs:element
<xs:element name="password">
name="password">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:string">
base="xs:string">
<xs:length
<xs:length value="8"/>
value="8"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
<xs:element
<xs:element name="password">
name="password">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:string">
base="xs:string">
<xs:minLength
<xs:minLength value="5"/>
value="5"/>
<xs:maxLength
<xs:maxLength value="8"/>
value="8"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
www.epam.com
Значение должно
содержать ровно
8 символов
Задаем максимальное
и минимальное
количество символов
EPAM Systems
19

20. Ограничения на пробельные символы

• Ограничение whiteSpace может принимать три значения:
• preserve – оставляет все пробелы, символы
табуляции и пустой строки как они есть
• replace – заменяет все такие символы на один пробел
• collapse – удаляет все пробелы спереди и сзади и
заменяет все промежуточные на одиночные пробелы
<xs:element
<xs:element name="address">
name="address">
<xs:simpleType>
<xs:simpleType>
<xs:restriction
<xs:restriction base="xs:string">
base="xs:string">
<xs:whiteSpace
<xs:whiteSpace value="preserve"/>
value="preserve"/>
</xs:restriction>
</xs:restriction>
</xs:simpleType>
</xs:simpleType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
20

21. Индикаторы (Indicators)

В XML Schema существуют 7 элементов-индикаторов которые
задают поведение элементов и атрибутов в XML
Индикаторы порядка:
• all
• choice
• sequence
Индикаторы вхождения:
• maxOccurs
• minOccurs
Индикаторы груп:
• group
• attributeGroup
www.epam.com
EPAM Systems
21

22. Индикаторы порядка

<xs:element
Элементы могут следовать
<xs:element name="person">
name="person">
в любом порядке
<xs:complexType>
<xs:complexType>
<xs:all>
<xs:all>
<xs:element
<xs:element name="firstname"
name="firstname" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="lastname"
name="lastname" type="xs:string"/>
type="xs:string"/>
</xs:all>
</xs:all>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
Только один из
представленных элементов
может присутствовать
<xs:element
<xs:element name="person">
name="person">
<xs:complexType>
<xs:complexType>
<xs:choice>
<xs:choice>
<xs:element
<xs:element name="employee"
name="employee" type="employee"/>
type="employee"/>
<xs:element
<xs:element name="member"
name="member" type="member"/>
type="member"/>
</xs:choice>
</xs:choice>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
22

23. Индикаторы порядка

<xs:element
<xs:element name="person">
name="person">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="firstname"
name="firstname" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="lastname"
name="lastname" type="xs:string"/>
type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
Элементы должны следовать
в заданном порядке
www.epam.com
EPAM Systems
23

24. Индикаторы вхождения

• Индикаторы вхождения показывают количество вхождений
элемента
• Если индикатор не указан, то по умолчанию должен быть
только один элемент. По умолчанию:
– minOccurs=1
– maxOccurs=1
<xs:element
<xs:element name="person">
name="person">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="full_name"
name="full_name" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="child_name"
name="child_name" type="xs:string"
type="xs:string"
maxOccurs="10"/>
maxOccurs="10"/>
</xs:sequence>
</xs:sequence>
Элемент <child_name> должен
</xs:complexType>
следовать за <full_name> и
</xs:complexType>
может быть представлен
</xs:element>
</xs:element>
минимум 1 и максимум 10 раз
www.epam.com
EPAM Systems
24

25. Индикаторы вхождения

• Индикатор maxOccurs может иметь минимальное
значение 1, а minOccurs значение 0
• Для указания любого количества вхождений ставим
maxOccurs="unbounded"
<xs:element
<xs:element name="person">
name="person">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="full_name"
name="full_name" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="child_name"
name="child_name" type="xs:string"
type="xs:string"
minOccurs="0"
minOccurs="0" maxOccurs="10"/>
maxOccurs="10"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
Элемент <child_name> может
</xs:element>
</xs:element>
отсутствовать либо должен
следовать за <full_name> в
количестве максимум 10 раз
www.epam.com
EPAM Systems
25

26. Индикаторы групп (Элемент group)

• Индикаторы групп объявляют связанные наборы элементов
или атрибутов для последующей ссылки на них
<xs:group
<xs:group name="persongroup">
name="persongroup">
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name="firstname"
name="firstname" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="lastname"
name="lastname" type="xs:string"/>
type="xs:string"/>
<xs:element
<xs:element name="birthday"
name="birthday" type="xs:date"/>
type="xs:date"/>
</xs:sequence>
</xs:sequence>
</xs:group>
</xs:group>
<xs:complexType
<xs:complexType name="personinfo">
name="personinfo">
<xs:sequence>
<xs:sequence>
<xs:group
<xs:group ref="persongroup"/>
ref="persongroup"/>
<xs:element
<xs:element name="country"
name="country" type="xs:string"/>
type="xs:string"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
<xs:element
<xs:element name="person"
name="person" type="personinfo"/>
type="personinfo"/>
www.epam.com
EPAM Systems
26

27. Индикаторы групп (Элемент attributeGroup)

• Элемент <attributeGroup> используется также как и
<group>
<xs:attributeGroup
<xs:attributeGroup name="personattrgroup">
name="personattrgroup">
<xs:attribute
<xs:attribute name="firstname"
name="firstname" type="xs:string"/>
type="xs:string"/>
<xs:attribute
<xs:attribute name="lastname"
name="lastname" type="xs:string"/>
type="xs:string"/>
<xs:attribute
<xs:attribute name="birthday"
name="birthday" type="xs:date"/>
type="xs:date"/>
</xs:attributeGroup>
</xs:attributeGroup>
<xs:element
<xs:element name="person">
name="person">
<xs:complexType>
<xs:complexType>
<xs:attributeGroup
<xs:attributeGroup ref="personattrgroup"/>
ref="personattrgroup"/>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
27

28. Уникальность (Элемент unique)

• Указывает, что значение атрибута или элемента
(либо их сочетание) должно быть уникально в
данной области видимости
<unique id=ID name=NCName
{any attributes with non-schema Namespace}...>
Content: (annotation?, selector, field+)
</unique>
www.epam.com
EPAM Systems
28

29. Уникальность – Пример

<?xml
<?xml version="1.0"?>
version="1.0"?>
<cities
<cities ...
... >>
<city
<city name="Milan"
name="Milan"
country="Italy"/>
country="Italy"/>
<city
<city name="Paris"
name="Paris"
country="France"/>
country="France"/>
<city
<city name="Munich"
name="Munich"
country="Germany"/>
country="Germany"/>
<city
<city name="Lyon"
name="Lyon"
country="France"/>
country="France"/>
<city
<city name="Venice"
name="Venice"
country="Italy"/>
country="Italy"/>
<city
<city name="Venice"
name="Venice"
country="Italy"/>
country="Italy"/>
</cities>
</cities>
www.epam.com
<xs:element
<xs:element name="cities">
name="cities">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element ref="e:city"
ref="e:city"
maxOccurs="unbounded"/>
maxOccurs="unbounded"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
<xs:unique
<xs:unique name="cityName">
name="cityName">
<xs:selector
<xs:selector xpath="e:city"/>
xpath="e:city"/>
<xs:field
<xs:field xpath="@name"/>
xpath="@name"/>
</xs:unique>
</xs:unique>
</xs:element>
</xs:element>
Нарушение
уникальности
EPAM Systems
29

30. Ключи (Элемент key)

• Указывает, что значение атрибута или элемента
(либо набор значений) должно быть ключом в
данной области видимости
• Ключ должен быть уникальным в пределах
конкретной области действия, не нулевым и
постоянно доступным
<key id=ID name=NCName
{any attributes with non-schema Namespace}...>
Content: (annotation?, selector, field+)
</key>
www.epam.com
EPAM Systems
30

31. Ссылки на ключи (Элемент keyref)

• Указывает, что значение атрибута или элемента (или набор
значений) соответствует значению указанного элемента key
или unique
<keyref id = ID name = NCName refer = QName
{any attributes with non-schema Namespace}...>
Content: (annotation?, selector, field+)
</keyref>
www.epam.com
EPAM Systems
31

32. Ключи – Пример

<?xml version="1.0"?>
<data ... >
<cities>
<city name="Milan"
country="Italy"/>
<city name="Paris"
country="France"/>
<city name="Munich"
country="Germany"/>
</cities>
<persons>
<person name="Paul"
city="Paris"/>
<person name="Jack"
city="London"/>
</persons>
</data>
www.epam.com
<xs:element name="data">
<xs:complexType>
...
</xs:complexType>
<xs:key name="cityName">
<xs:selector
xpath="e:cities/e:city"/>
<xs:field xpath="@name"/>
</xs:key>
<xs:keyref name="personCity"
refer="e:cityName">
<xs:selector
xpath="e:persons/e:person"/>
<xs:field xpath="@city"/>
</xs:keyref>
</xs:element>
Ключевое
значение
отсутствует
EPAM Systems
32

33. Использование содержимого других схем

• Элемент <any> используется для добавления элемента из
другого пространства имен
• Элемент <any> может быть дочерним для <group>,
<sequence>, <all> или <choice>.
<xs:element
<xs:element name="catalog">
name="catalog">
<xs:complexType>
<xs:complexType>
<xs:sequence>
<xs:sequence>
<xs:any
<xs:any namespace="http://www.fabrikam.com/catalog"
namespace="http://www.fabrikam.com/catalog"
minOccurs="0"
minOccurs="0" maxOccurs="unbounded"
maxOccurs="unbounded"
processContents="skip"/>
processContents="skip"/>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
</xs:element>
</xs:element>
www.epam.com
EPAM Systems
33

34. Документирование схем

• Можно использовать обычные XML комментарии
<!-- This is a comment -->
• Аннотации могут появляться везде в схеме
– <annotation> - родительский для <appinfo> и <documentation>
– <appinfo> - предоставляет информацию для внешних приложений
– <documentation> - позволяет размещать комментарии для разработчиков
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:annotation>
<xs:appinfo>Schema for processing submitted applications</xs:appinfo>
<xs:documentation>Submitted for Human Resources</xs:documentation>
</xs:annotation>
<xs:element name="relocationStatus">
<xs:complexType>
<xs:annotation>
<xs:appinfo>No further processing is required.</xs:appinfo>
<xs:documentation>This element is for determining relocation
status to determine help determine costs.</xs:documentation>
</xs:annotation>
</xs:complexType>
</xs:element>
</xs:schema>
www.epam.com
EPAM Systems
34

35. Описание ссылки на XSD в XML

<?xml
<?xml version="1.0"?>
version="1.0"?>
<note
<note xmlns="http://www.epam.com"
xmlns="http://www.epam.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.epam.com
xsi:schemaLocation="http://www.epam.com note.xsd">
note.xsd">
<to>Tove</to>
<to>Tove</to>
Местоположение
<from>Jani</from>
<from>Jani</from>
схемы
<heading>Reminder</heading>
<heading>Reminder</heading>
<body>Don't
<body>Don't forget
forget me
me this
this weekend!</body>
weekend!</body>
Пространство
</note>
</note>
имен
• xmlns="http://www.epam.com" - пространство имен по умолчанию
• xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - пространство
имен экземпляра схемы одним из имен в котором является атрибут
schemaLocation
• xsi:schemaLocation="http://www.epam.com note.xsd" - определяет какой
схеме (пространству имен) соответствует данный XML и где находится схема
для валидации данного XML
www.epam.com
EPAM Systems
35

36. Описание ссылки на XSD в XML


xsi:noNamespaceSchemaLocation используется, когда не используются
пространства имен
<book
<book xsi:noNamespaceSchemaLocation="http://www.epam.com/epam.xsd">
xsi:noNamespaceSchemaLocation="http://www.epam.com/epam.xsd">
<title>Presenting
<title>Presenting XML</title>
XML</title>
<author>Richard
<author>Richard Light</author>
Light</author>
</book>
</book>
Можно использовать URL файловой системы
xsi:noNamespaceSchemaLocation=“file:///d:/xml/schemas/epam.xsd"
xsi:noNamespaceSchemaLocation=“file:///d:/xml/schemas/epam.xsd"
xsi:schemaLocation используется, когда префиксы пространств имен явно
определены и используются
<data:catalog
<data:catalog xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:data="http://www.epam.com"
xmlns:data="http://www.epam.com"
xsi:schemaLocation="http://www.epam.com
xsi:schemaLocation="http://www.epam.com
http://www.epam.com/epam.xsd">
http://www.epam.com/epam.xsd">
...
...
</data:catalog>
</data:catalog>
www.epam.com
EPAM Systems
36

37. Задание

<?xml
<?xml version="1.0"
version="1.0" encoding="UTF-8"
encoding="UTF-8" standalone="yes"?>
standalone="yes"?>
<!DOCTYPE
<!DOCTYPE Data>
Data>
<Data>
<Data>
<Customers>
<Customers>
<Customer>John</Customer>
<Customer>John</Customer>
</Customers>
</Customers>
<Items>
<Items>
<Item>Item1</Item>
<Item>Item1</Item>
Создать схему,
<Item>Item2</Item>
<Item>Item2</Item>
описывающую подобную
</Items>
</Items>
структуру данных
<Orders>
<Orders>
<Order>
<Order>
<Customer>John</Customer>
<Customer>John</Customer>
<Item
<Item count="5">Item1</Item>
count="5">Item1</Item>
<Item
<Item count="2">Item2</Item>
count="2">Item2</Item>
</Order>
</Order>
</Orders>
</Orders>
</Data>
</Data>
www.epam.com
EPAM Systems
37

38.

Спасибо за внимание!
Контактная информация:
Денис Мурашев
Инструктор
EPAM Systems, Inc.
Адрес: Саратов, Рахова, 181
Email: Denis_Murashev@epam.com
http://www.epam.com
www.epam.com
EPAM Systems
38
English     Русский Rules