Валидация xml с помощью xsd, jaxb и spring framework

1 Motivation and Summary

We envision applications of Extensible Markup Language (XML) where a single XML document may contain elements and attributes (here referred to as a «markup vocabulary») that are defined for and used by multiple software modules. One motivation for this is modularity: if such a markup vocabulary exists which is well-understood and for which there is useful software available, it is better to re-use this markup rather than re-invent it.

Such documents, containing multiple markup vocabularies, pose problems of recognition and collision. Software modules need to be able to recognize the elements and attributes which they are designed to process, even in the face of «collisions» occurring when markup intended for some other software package uses the same element name or attribute name.

These considerations require that document constructs should have names constructed so as to avoid clashes between names from different markup vocabularies. This specification describes a mechanism, XML namespaces, which accomplishes this by assigning to elements and attributes.

7 Conformance of Documents

This specification applies to XML 1.0 documents. To conform to this specification, a document MUST be well-formed according to the XML 1.0 specification .

In XML documents which conform to this specification, element and attribute names MUST match the production for

and MUST satisfy the «Namespace Constraints». All other tokens in the document which are REQUIRED,

for XML 1.0 well-formedness, to match the XML production for

MUST match this specification’s production for .

[Definition: A document is namespace-well-formed if it conforms to this specification. ]

It follows that in a namespace-well-formed document:

  • All element and attribute names contain either zero or one colon;

  • No entity names, processing instruction targets, or notation names contain any colons.


In addition, a namespace-well-formed document may also be namespace-valid.

[Definition: A namespace-well-formed document is namespace-valid if it is valid according to the XML 1.0 specification, and all tokens other than element and attribute names which are REQUIRED, for XML 1.0 validity, to match the XML production for

match this specification’s production for . ]

It follows that in a namespace-valid document:

Создание XML-схемы

Теперь мы хотим создать схему для документа XML выше.

Мы начнем с открытия нового файла , который мы будем называть «shiporder.xsd» . Для того, чтобы создать схему мы могли бы просто следовать структуре в документе XML и определите каждый элемент, как мы находим его. Мы начнем со стандартной декларации XML с последующим хз: элемент схемы, который определяет схему:

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

В схеме выше мы используем стандартные пространства имен (xs) , и URI , связанный с этим пространством имен является определение языка схемы, который имеет стандартное значение http://www.w3.org/2001/XMLSchema.

Далее, мы должны определить «shiporder» элемент. Этот элемент имеет атрибут и содержит другие элементы, поэтому мы рассматриваем его как сложный тип. Дочерние элементы «shiporder» элемент окружен хз: элемент последовательности , которая определяет упорядоченную последовательность субэлементов:

<xs:element name=»shiporder»>   <xs:complexType>     <xs:sequence>       …     </xs:sequence>   </xs:complexType> </xs:element>

Затем мы должны определить «orderperson» элемент в качестве простого типа (так как она не содержит каких — либо атрибутов или других элементов). В типа (xs:string) с префиксом префикс пространства имен , связанного с XML — схемы , которая указывает заранее определенный тип данных схемы:

<xs:element name=»orderperson» type=»xs:string»/>

Далее, мы должны определить два элемента , которые имеют сложного типа: «shipto» и «item» . Мы начнем с определения «shipto» элемент:

<xs:element name=»shipto»>   <xs:complexType>     <xs:sequence>       <xs:element name=»name» type=»xs:string»/>       <xs:element name=»address» type=»xs:string»/>       <xs:element name=»city» type=»xs:string»/>       <xs:element name=»country» type=»xs:string»/>     </xs:sequence>   </xs:complexType> </xs:element>

С помощью схем, которые мы можем определить количество возможных появлений для элемента с MaxOccurs и атрибутами MinOccurs. MaxOccurs определяет максимальное число вхождений для элемента и MinOccurs определяет минимальное число вхождений для элемента. Значение по умолчанию для обоих MaxOccurs и MinOccurs 1!

Теперь мы можем определить «item» элемент. Этот элемент может появляться несколько раз внутри «shiporder» элемента. Это определяется установкой maxOccurs атрибут «item» элемента «unbounded» , что означает , что там может быть много вхождений «item» элемент , как автор хочет

Обратите внимание на то, что «note» элемент не является обязательным. Мы определили это, установив minOccurs атрибут к нулю:

<xs:element name=»item» maxOccurs=»unbounded»>   <xs:complexType>     <xs:sequence>       <xs:element name=»title» type=»xs:string»/>       <xs:element name=»note» type=»xs:string» minOccurs=»0″/>       <xs:element name=»quantity» type=»xs:positiveInteger»/>       <xs:element name=»price» type=»xs:decimal»/>     </xs:sequence>   </xs:complexType> </xs:element>

Теперь мы можем объявить атрибут «shiporder» элемента. Поскольку это обязательный атрибут мы указываем использование = «требуется».

Note: Заявления атрибутов всегда должны прийти в последний раз :

<xs:attribute name=»orderid» type=»xs:string» use=»required»/>

Вот полный список файла схемы под названием «shiporder.xsd» :

<?xml version=»1.0″ encoding=»UTF-8″ ?> <xs:schema xmlns:xs=»http://www.w3.org/2001/XMLSchema»> <xs:element name=»shiporder»>   <xs:complexType>     <xs:sequence>       <xs:element name=»orderperson» type=»xs:string»/>       <xs:element name=»shipto»>         <xs:complexType>           <xs:sequence>             <xs:element name=»name» type=»xs:string»/>             <xs:element name=»address» type=»xs:string»/>             <xs:element name=»city» type=»xs:string»/>             <xs:element name=»country» type=»xs:string»/>           </xs:sequence>         </xs:complexType>       </xs:element>       <xs:element name=»item» maxOccurs=»unbounded»>         <xs:complexType>           <xs:sequence>             <xs:element name=»title» type=»xs:string»/>             <xs:element name=»note» type=»xs:string» minOccurs=»0″/>             <xs:element name=»quantity» type=»xs:positiveInteger»/>             <xs:element name=»price» type=»xs:decimal»/>           </xs:sequence>         </xs:complexType>       </xs:element>     </xs:sequence>     <xs:attribute name=»orderid» type=»xs:string» use=»required»/>   </xs:complexType> </xs:element> </xs:schema>

XML Elements are Extensible

XML elements can be extended to carry more information.

Look at the following XML example:

<note>   <to>Tove</to>   <from>Jani</from>   <body>Don’t forget me this weekend!</body> </note>

Let’s imagine that we created an application that extracted the <to>, <from>, and <body> elements from the XML document to produce this output:

MESSAGE

To: ToveFrom: Jani

Don’t forget me this weekend!

Imagine that the author of the XML document added some extra information to it:

<note>   <date>2008-01-10</date>   <to>Tove</to>   <from>Jani</from>   <heading>Reminder</heading>   <body>Don’t forget me this weekend!</body> </note>

Should the application break or crash?

No. The application should still be able to find the <to>, <from>, and <body> elements in the XML document and produce the same output.

This is one of the beauties of XML. It can be extended without breaking applications.

W3C Working Group Note 16 December 2010

This version:
http://www.w3.org/TR/2010/NOTE-xhtml-role-20101216
Latest version:
http://www.w3.org/TR/xhtml-role
Previous version:
http://www.w3.org/TR/2008/WD-xhtml-role-20080407
Diff from previous version:
xhtml-role-diff.html
Editors:
Mark Birbeck, Sidewinder Labs mark.birbeck@sidewinderlabs.com
Shane McCarron, Applied Testing and Technology, Inc.
Steven Pemberton, CWI/W3C
T. V. Raman, Google, Inc.
Richard Schwerdtfeger, IBM Corporation

This document is also available in these non-normative formats: PostScript version, PDF version, ZIP archive, and Gzip’d TAR archive.

The English version of this specification is the only normative version. Non-normative translations may also be available.

7.2. The head element

The element contains information about the current document, such as its title, that is not considered document content. The default presentation of the head is not to display it; however that can be overridden with a style sheet for special purpose use. User agents may however make information in the

available to users through other mechanisms.

Attributes

The collection
A collection of other attribute collections, including: , , , , , , , , , , and
profile =
This attribute specifies the location of one or more metadata profiles, separated by white space. For future extensions, user agents should consider the value to be a list even though this specification only considers the first URI to be significant. Profiles are discussed in the section on .

Example

<head>
	<title>My Life</title>
</head>

XML is Extensible

Most XML applications will work as expected even if new data is added (or removed).

Imagine an application designed to display the original version of note.xml (<to> <from> <heading> <body>).

Then imagine a newer version of note.xml with added <date> and <hour> elements, and a removed <heading>.

The way XML is constructed, older version of the application can still work:

<note>   <date>2015-09-01</date>  <hour>08:30</hour>  <to>Tove</to>   <from>Jani</from>   <body>Don’t forget me this weekend!</body> </note>

To: Tove

From: Jani

New Version

To: Tove

From: Jani

Date: 2015-09-01 08:30

XML Simplifies Things

  • It simplifies data sharing
  • It simplifies data transport
  • It simplifies platform changes
  • It simplifies data availability

Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost.

XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.

With XML, data can be available to all kinds of «reading machines» like people, computers, voice machines, news feeds, etc.

XML became a W3C Recommendation as early as in February 1998.

B.1. Attributes Module

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 elementFormDefault="qualified"
 xmlns:xh11d="http://www.w3.org/1999/xhtml/datatypes/"
>
    <xs:import namespace="http://www.w3.org/1999/xhtml/datatypes/" 
               schemaLocation="xhtml-datatypes-1.xsd" />

    <xs:annotation>
        <xs:documentation>
      This is the XML Schema attribute module for XHTML Role
      $Id: Overview.html,v 1.5 2018/10/09 13:22:52 denis Exp $
    </xs:documentation>
        <xs:documentation source="xhtml-copyright-1.xsd"/>
        <xs:documentation source="http://www.w3.org/TR/xhtml-role#A_role"/>
    </xs:annotation>
    <xs:attribute name="role" type="xh11d:CURIEs"/>
</xs:schema>

Naming Styles

There are no naming styles defined for XML elements. But here are some commonly used:

Style Example Description
Lower case <firstname> All letters lower case
Upper case <FIRSTNAME> All letters upper case
Underscore <first_name> Underscore separates words
Pascal case <FirstName> Uppercase first letter in each word
Camel case <firstName> Uppercase first letter in each word except the first

If you choose a naming style, it is good to be consistent!

XML documents often have a corresponding database. A common practice is to use the naming rules of the database for the XML elements.

Camel case is a common naming rule in JavaScripts.

3 Language and Processing

This section describes the syntax and semantics of the scheme and the behavior of XPointer processors with respect to this scheme.

The scheme name is «xmlns». The scheme data syntax is as follows; if scheme data in a pointer part with the scheme does not conform to the syntax defined in this section the pointer part does not contribute an entry to the namespace binding context.

xmlns() Scheme Syntax
       ::=   
       ::=   

is as defined in the XML specification , is as defined in the XML Namespaces specification , and is as defined in the XPointer Framework specification .

A pointer part with the scheme declares a namespace prefix () to be associated with an XML namespace name ( with any circumflex-escaping undone). Each pointer part that uses the scheme contributes a new entry to the namespace binding context. If a pointer part defines a binding for a namespace prefix that already has an entry in the namespace binding context, the new entry overrides the old one.

For example, the following pointer part binds the abc prefix to the http://example.com/ns/abc namespace name:

xmlns(abc=http://example.com/ns/abc)

A pointer part that uses the scheme never identifies a subresource and thus the XPointer processor evaluation always continues with the next pointer part. However, evaluation of the pointer part has a potential effect on pointer parts to its right.


The XPointer Framework on which this specification is based dictates that the initial namespace binding context prior to evaluation of the first pointer part consists of a single entry: the prefix bound to the URI . Following the rules specified by the Framework, any attempt by a pointer part using the scheme to redefine the prefix will result in no change to the namespace binding context. Any attempt to bind a prefix to the namespace name will result in no change to the namespace binding context. Any attempt to define the prefix will result in no change to the namespace binding context. Any attempt to bind a prefix to the namespace name will result in no change to the namespace binding context.

The prefix used in pointer parts need not match the prefix (or lack of a prefix) actually used in the XML resource into which the pointer part is addressing. For example, assume the following target XML resource:

<customer xmlns="http://example.org/customer">
   <name xmlns="http://example.org/personal-info">John Doe</name>
</customer>

Evaluation of a pointer part that refers to element will not identify any subresources if the namespace binding context contains no entry that binds a prefix to the namespace name . The following two pointer parts allow the xpointer() part to the right to refer to the element (as ) and the name element (as ):

Синтаксис¶

Атрибуты:

необязательный атрибут, который определяет, какой метод должен использоваться для вывода документа. Значением этого атрибута может быть любое имя, но при этом техническая рекомендация XSLT определяет только три стандартных метода вывода — «», «» и «». В том случае, если процессор поддерживает нестандартный метод вывода, его реализация полностью зависит от производителя. Если в преобразовании не определен элемент или в нем не указан атрибут , метод преобразования выбирается по умолчанию исходя из следующих условий.
необязательный атрибут, определяет версию языка выходящего документа;
необязательный атрибут, определяет, должен ли процессор добавлять пробельные символы для более наглядного форматирования документа;
необязательный атрибут, определяет, в какой кодировке должен быть выведен документ. Значение этого атрибута не зависит от регистра символов, то есть значения и будут эквивалентны. В атрибуте можно использовать только печатаемые символы , то есть символы интервала от до . Значением должно быть название набора символов, определенное в стандартах IANA (Internet Assigned Numbers Authority) или RFC2278. В противном случае, атрибут должен начинаться символами «»;
необязательный атрибут, определяет тип содержимого MIME выходящего документа;
необязательный атрибут, определяет системный идентификатор, который должен быть использован в декларации типа документа ();
необязательный атрибут, определяет публичный идентификатор, который должен быть использован в декларации типа документа ();
необязательный атрибут, определяет, нужно ли включать декларацию XML в выходящий документ или нет. Значением этого атрибута должно быть либо «» (пропустить декларацию), либо «» (включить декларацию в выходящий документ);
необязательный атрибут, определяет, должен ли процессор выводить указание на самостоятельность документа (standalone declaration). Значением этого атрибута может быть либо «» (выводить указание), либо «» (не выводить указание на самостоятельность);
необязательный атрибут, определяет список элементов, текстовое содержимое которых должно быть выведено с использованием секций .

Использование этих атрибутов зависит от того, какой из методов выбран для вывода преобразованного документа.

The SOAP Body Element

The required SOAP Body element contains the actual SOAP message intended for the ultimate endpoint of the message.

Immediate child elements of the SOAP Body element may be namespace-qualified.

Example

<?xml version=»1.0″?><soap:Envelope xmlns:soap=»http://www.w3.org/2003/05/soap-envelope/» soap:encodingStyle=»http://www.w3.org/2003/05/soap-encoding»> <soap:Body>   <m:GetPrice xmlns:m=»https://www.w3schools.com/prices»>     <m:Item>Apples</m:Item>   </m:GetPrice> </soap:Body> </soap:Envelope>

The example above requests the price of apples. Note that the m:GetPrice and the Item elements above are application-specific elements. They are not a part of the SOAP namespace.

A SOAP response could look something like this:

<?xml version=»1.0″?><soap:Envelope xmlns:soap=»http://www.w3.org/2003/05/soap-envelope/» soap:encodingStyle=»http://www.w3.org/2003/05/soap-encoding»> <soap:Body>   <m:GetPriceResponse xmlns:m=»https://www.w3schools.com/prices»>     <m:Price>1.90</m:Price>   </m:GetPriceResponse> </soap:Body> </soap:Envelope>

7.3. The title element

Every XHTML document must have a

element in the

section.

Attributes

The collection
A collection of other attribute collections, including: , , , , , , , , , , and

The element is used to provide identification for a document or a section of a document. Since documents are often consulted out of context, authors should provide context-rich titles. Thus, instead of a title such as «Introduction», which doesn’t provide much contextual background, authors should supply a title such as «Introduction to Medieval Bee-Keeping» instead.

For reasons of accessibility, user agents must always make the content of the element available to users. The mechanism for doing so depends on the user agent (e.g., as a caption, spoken).

When is used in within the

element of a document, that title applies to the entire document. When used elsewhere, it applies to its enclosing element.

Example

<title>A study of population dynamics</title>

Example

<section>
    <title>Intoroduction to Medieval Bee-Keeping</title>
    <p>Some information about....</p>
</section>

The title of a document is metadata about the document, and so a title like is equivalent to .

Особенности XML

  • Цели разработки XML делают упор на универсальность, удобство использования и простоту данных в Интернете.
  • XML служит текстовым форматом данных, который имеет сильную поддержку через Unicode для различных человеческих языков.
  • XML в основном фокусируется на документах, но в значительной степени используется для представления произвольных структур данных, как в случае тех, которые используются в веб-сервисах.

Используемый большинством разработчиков программного обеспечения, XML — это будущее для манипулирования данными в веб-разработке. Основные области использования:

  • XML хранит данные в отдельном месте от HTML, поэтому любые изменения, внесенные в HTML-коды, не влияют на XML-документы. Учитывая это, программисты могут сконцентрироваться на использовании HTML только с целью форматирования и отображения.
  • XML хранит данные внутри документов HTML. Эти данные находят место в документах HTML как «острова данных». HTML-коды могут использоваться для форматирования и отображения данных, в то время как «острова данных» используются только для целей хранения.
  • XML может использоваться в качестве предпочтительного формата для обмена информацией. Данные XML легко конвертируются и снижают сложность для разработчиков, использующих системы вычислений и базы данных. После преобразования данные XML легко расшифровываются и читаются всеми видами приложений.
  • XML используется для хранения данных в базах данных и файлах. Таким образом, приложения могут быть написаны для хранения и восстановления информации с жестких дисков. Кроме того, могут быть созданы универсальные приложения для отображения определенных видов данных.

Viewing XML Files

<?xml version=»1.0″ encoding=»UTF-8″?> — <note>        <to>Tove</to>        <from>Jani</from>        <heading>Reminder</heading>        <body>Don’t forget me this weekend!</body>    </note>

Look at the XML file above in your browser: note.xml

Most browsers will display an XML document with color-coded elements.

Often a plus (+) or minus sign (-) to the left of the elements can be clicked to expand or collapse the element structure.

To view raw XML source, try to select «View Page Source» or «View Source» from the browser menu.

Note: In Safari 5 (and earlier), only the element text will be displayed. To view the raw XML, you must right click the page and select «View Source».

XML Simplifies Things

  • It simplifies data sharing
  • It simplifies data transport
  • It simplifies platform changes
  • It simplifies data availability

Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost.

XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.

With XML, data can be available to all kinds of «reading machines» like people, computers, voice machines, news feeds, etc.

3 Declaring Namespaces

[Definition: A namespace (or more precisely, a namespace binding) is declared using a family of reserved attributes. Such an attribute’s name must either be xmlns or begin xmlns:. These attributes, like any other XML attributes, may be provided directly or by . ]

Attribute Names for Namespace Declaration
       ::=   
       ::=   
       ::=   
       ::=    /* An XML , minus the «:» */

The attribute’s

MUST be either

a URI reference — the

identifying the namespace — or an empty string.

The namespace name, to serve its intended purpose, SHOULD have the characteristics of uniqueness and persistence. It is not a goal that it be directly usable for retrieval of a schema (if any exists). Uniform Resource Names is an example of a syntax that is designed with these goals in mind. However, it should be noted that ordinary URLs can be managed in such a way as to achieve these same goals.

[Definition: If the attribute name matches , then the gives the namespace prefix, used to associate element and attribute names with the in the attribute value in the scope of the element to which the declaration is attached.

[Definition: If the attribute name matches , then the in the attribute value is that of the default namespace in the scope of the element to which the declaration is attached.] Default namespaces and overriding of declarations are discussed in .

An example namespace declaration, which associates the namespace prefix edi with the namespace name :

<x xmlns:edi='http://ecommerce.example.org/schema'>
  <!-- the "edi" prefix is bound to http://ecommerce.example.org/schema
       for the "x" element and contents -->
</x>

Namespace constraint: Reserved Prefixes and Namespace Names

The prefix xml is by definition bound to the namespace name . It MAY, but need not, be declared, and MUST NOT be

bound to any other namespace name. Other prefixes MUST NOT be bound to this namespace name, and it MUST NOT be declared as the default namespace.

The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name . It MUST NOT be declared . Other prefixes MUST NOT be bound to this namespace name, and it MUST NOT be declared as the default namespace.

Element names MUST NOT have the prefix .

All other prefixes beginning with the three-letter sequence x, m, l, in any case combination, are reserved. This means that:

  • users SHOULD NOT use them except as defined by later specifications

  • processors MUST NOT treat them as fatal errors.

XML Namespaces — The xmlns Attribute

When using prefixes in XML, a namespace for the prefix must be defined.

The namespace can be defined by an xmlns attribute in the start tag of an element.

The namespace declaration has the following syntax. xmlns:prefixURI«.

<root> <h:table xmlns:h=»http://www.w3.org/TR/html4/»>   <h:tr>     <h:td>Apples</h:td>     <h:td>Bananas</h:td>   </h:tr> </h:table> <f:table xmlns:f=»https://www.w3schools.com/furniture»>   <f:name>African Coffee Table</f:name>   <f:width>80</f:width>   <f:length>120</f:length> </f:table> </root>

In the example above:

The xmlns attribute in the first <table> element gives the h: prefix a qualified namespace.

The xmlns attribute in the second <table> element gives the f: prefix a qualified namespace.

When a namespace is defined for an element, all child elements with the same prefix are associated with the same namespace.

Namespaces can also be declared in the XML root element:

<root xmlns:h=»http://www.w3.org/TR/html4/» xmlns:f=»https://www.w3schools.com/furniture»> <h:table>   <h:tr>     <h:td>Apples</h:td>     <h:td>Bananas</h:td>   </h:tr> </h:table> <f:table>   <f:name>African Coffee Table</f:name>   <f:width>80</f:width>   <f:length>120</f:length> </f:table> </root>

Note: The namespace URI is not used by the parser to look up information.

The purpose of using an URI is to give the namespace a unique name.

However, companies often use the namespace as a pointer to a web page containing namespace information.

HTML Tags

<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

W3C Recommendation 25 March 2003

This version:
http://www.w3.org/TR/2003/REC-xptr-xmlns-20030325/
Latest version:
http://www.w3.org/TR/xptr-xmlns/
Previous version:
http://www.w3.org/TR/2002/PR-xptr-xmlns-20021113/
Editors:
Steven J. DeRose <sderose@acm.org>
Ron Daniel Jr. <rdaniel@taxonomystrategies.com>
Eve Maler, Sun Microsystems <eve.maler@sun.com>
Jonathan Marsh, Microsoft <jmarsh@microsoft.com>

Please refer to the errata for this document, which may include some normative corrections.

This document is also available in these non-normative formats: XML.

The English version of this specification is the only normative version. Non-normative translations may also be available.

2.1. Document Conformance

XHTML Role Attribute Module is not a stand-alone document type. It is intended to be integrated into other host languages such as XHTML. A conforming XHTML Role Attribute Module document is a document that requires only the facilities described as mandatory in this specification and the facilities described as mandatory in its host language. Such a document must meet all the following criteria:

  1. The document MUST conform to the constraints expressed in its host language implementation.

  2. If the host language is in the XHTML Namespace, there are no additional requirements. If the host language is not in the XHTML namespace, and the host language does not incorporate this module into its own namespace, then the document MUST contain an XML namespace declaration for the XHTML Role Attribute Module namespace []. The namespace for XHTML Role Attribute Module is defined to be . An example start tag of a root element might look like:

    This example is informative

    <mylang xmlns="http://www.example.com/dtd/mylang" 
            xmlns:xh="http://www.w3.org/1999/xhtml" xml:lang="en" >
    

2 XML Namespaces

2.1 Basic Concepts

[Definition: An XML namespace is identified by

a URI reference ; element and attribute names may be placed in an XML namespace using the mechanisms described in this specification. ]

[Definition: An expanded name is a pair consisting of a

and a . ]

[Definition: For a name N in a namespace identified by

a URI I, the namespace name is I. For a name N that is not in a namespace, the namespace name has no value. ]

[Definition: In either case the local name is N. ]

It is this combination of the universally managed URI namespace with the vocabulary’s local names that is effective in avoiding name clashes.

URI references can contain characters not allowed in names, and are often inconveniently long, so expanded names are not used directly to name elements and attributes in XML documents. Instead

are used. [Definition: A qualified name is a name subject to namespace interpretation. ] In documents conforming to this specification, element and attribute names appear as qualified names. Syntactically, they are either or . An attribute-based declaration syntax is provided to bind prefixes to namespace names and to bind a default namespace that applies to unprefixed element names; these declarations are scoped by the elements on which they appear so that different bindings may apply in different parts of a document. Processors conforming to this specification MUST recognize and act on these declarations and prefixes.

2.2 Use of URIs as Namespace Names

The empty string, though it is a legal

URI reference, cannot be used as a namespace name.

The use of relative

URI references, including same-document references, in namespace declarations is deprecated.

Note:

This deprecation of relative URI references was decided on by a W3C XML Plenary Ballot . It also declares that «later specifications such as DOM, XPath, etc. will define no interpretation for them».

Entity References

Some characters have a special meaning in XML.

If you place a character like «<» inside an XML element, it will generate an error because the parser interprets it as the start of a new element.

This will generate an XML error:

<message>salary < 1000</message>

To avoid this error, replace the «<» character with an entity reference:

<message>salary &lt; 1000</message>

There are 5 pre-defined entity references in XML:

&lt; < less than
&gt; > greater than
&amp; & ampersand 
&apos; apostrophe
&quot; « quotation mark

Only < and & are strictly illegal in XML, but it is a good habit to replace > with &gt; as well.

W3C Recommendation 8 December 2009

This version:

http://www.w3.org/TR/2009/REC-xml-names-20091208/

Latest version:

http://www.w3.org/TR/xml-names/

Previous versions:

http://www.w3.org/TR/2006/REC-xml-names-20060816/ http://www.w3.org/TR/2009/PER-xml-names-20090806/

Editors:
Tim Bray, Textuality <tbray@textuality.com>
Dave Hollander, Contivo, Inc. <dmh@contivo.com>
Andrew Layman, Microsoft <andrewl@microsoft.com>
Richard Tobin, University of Edinburgh and Markup Technology Ltd <richard@inf.ed.ac.uk>
Henry S. Thompson, University of Edinburgh and W3C <ht@w3.org> — Third Edition

Please refer to the errata for this document, which may include normative corrections.

See also translations.

This document is also available in these non-normative formats: XML and HTML highlighting differences from the second edition.

Applying Namespaces to Elements and Attributes

5.1 Namespace Scoping

The namespace declaration is considered to apply to the element where it is specified and to all elements within the content of that element, unless overridden by another namespace declaration with the same part:

Multiple namespace prefixes can be declared as attributes of a single element, as shown in this example:

5.2 Namespace Defaulting

A is considered to apply to the element where it is declared (if that element has no ), and to all elements with no prefix within the content of that element. If the URI reference in a default namespace declaration is empty, then unprefixed elements in the scope of the declaration are not considered to be in any namespace. Note that default namespaces do not apply directly to attributes.

A larger example of namespace scoping:

The default namespace can be set to the empty string. This has the same effect, within the scope of the declaration, of there being no default namespace.

5.3 Uniqueness of Attributes

In XML documents conforming to this specification, no tag may contain two attributes which:

  1. have identical names, or
  2. have qualified names with the same and with which have been bound to that are .

For example, each of the start-tags is illegal in the following:

However, each of the following is legal, the second because the default namespace does not apply to attribute names:


С этим читают