Default Namespaces
A «default namespace» is a namespace declaration that does not use a namespace prefix (See Figure 11 for notation method). The scope of the default namespace is the element for which the namespace was declared and the related content, just as with the namespace scope discussed earlier. The benefit of using a default namespace is that the namespace prefix can be omitted.
For example, when adding a new namespace to an existing XML document, writing a namespace prefix for each element to which the new namespace will be applied involves a tremendous amount of tedious work. The larger the XML document, the greater the labor involved, and the greater the likelihood of notation errors. In this type of situation, adding only a default namespace declaration to the XML document in question eliminates the need to write a namespace prefix for each and every element, saving a lot of time.
On the other hand, there are drawbacks. One drawback is that omitting the namespace prefix makes it more difficult to understand which element belongs to which namespace, and which namespace is applicable. In addition, programmers should remember that when a default namespace is declared, the namespace is applied only to the element, and not to any attributes.
Namespaces with Attributes
Attributes can either belong to the same namespace of the element for which the attribute is defined, or belong to a completely different namespace than that to which the element belongs. The definition for an attribute that belongs to a namespace is the same as that for elements, with the «namespacePrefix:» notation coming before the attribute name. If no namespace prefix is provided for the attribute name, the attribute will not belong to any namespace.
●Attribute belongs to same namespace as the element
<emp:employee xmlns:emp=»urn:corp:emp»>
<emp:personInfo emp:empID=»E0000001″>
<emp:secID>S001</emp:secID>
<emp:name>John Smith</emp:name>
</emp:personInfo>
</emp:employee>
●Attribute belongs to different namespace than the element
<emp:employee xmlns:emp=»urn:corp:emp»>
<emp:personInfo work:empID=»E0000001″
xmlns:work=»urn:corp:work»>
<emp:secID>S001</emp:secID>
<emp:name>John Smith</emp:name>
</emp:personInfo>
</emp:employee>
●Attribute does not belong to any namespace
<emp:employee xmlns:emp=»urn:corp:emp»>
<emp:personInfo empID=»E0000001″>
<emp:secID>S001</emp:secID>
<emp:name>John Smith</emp:name>
</emp:personInfo>
</emp:employee>
What must be noted here is that under the XML 1.0 specification, attributes with the same name cannot be written within the same element. However, for XML documents conforming to the Namespaces in XML specification, the combination of namespace identifier and attribute name is what determines whether an attribute is duplicated. Accordingly, if the namespace identifier is different, attributes having the same attribute name are considered to be different.
●The example below throws an error under the XML 1.0 specification
<employee>
<personInfo empID=»E0000001″ empID=»S0000001″>
<secID>S001</secID>
<name>John Smith</name>
</personInfo>
</employee>
●The example below does not throw an error, since the Namespaces in XML specification is used
<emp:employee xmlns:emp=»urn:corp:emp»
xmlns:work=»urn:corp:work»>
<emp:personInfo emp:empID=»E0000001″
work:empID=»S0000001″>
<emp:secID>S001</emp:secID>
<emp:name>John Smith</emp:name>
</emp:personInfo>
</emp:employee>
5 Using Qualified Names
In XML documents conforming to this specification,
element names are given as
, as
follows:
Element Names
::= | ||||
::= | ||||
::= |
An example of a qualified name serving as an element name:
<!-- the 'price' element's namespace is http://ecommerce.example.org/schema --> <edi:price xmlns:edi='http://ecommerce.example.org/schema' units='Euro'>32.18</edi:price>
Attributes are either
or their names are given as
:
Attribute
::= | ||||
An example of a qualified name serving as an attribute name:
<x xmlns:edi='http://ecommerce.example.org/schema'> <!-- the 'taxClass' attribute's namespace is http://ecommerce.example.org/schema --> <lineItem edi:taxClass="exempt">Baby food</lineItem> </x>
Namespace constraint: Prefix Declared
The namespace prefix, unless it is
or ,
MUST
have been
declared in a
attribute in either the start-tag of the element where the prefix
is used or in an ancestor element (i.e., an element in whose
the
prefixed markup occurs).
Namespace constraint: No Prefix Undeclaring
In a for a (i.e.,
where the is a ), the MUST NOT be empty.
This constraint may lead to operational difficulties in the case where
the namespace declaration attribute is provided, not directly in the XML
, but
via a default attribute declared in an external entity.
Such declarations may not be read by software which is based on a
non-validating XML processor.
Many XML applications, presumably including namespace-sensitive ones, fail to
require validating processors.
If correct operation with such applications is required,
namespace declarations
MUST
be
provided either directly or via default attributes declared in the
.
Element names and attribute names are also given as qualified names when
they appear in declarations in the
:
XML-пространства имен — атрибут XMLNS
При использовании префиксов в XML, должны быть определены так называемоепространство имен для префикса.
Пространство именXMLNS атрибут определен в начальный тег элемента.
Синтаксис пространство имен декларации заключается в следующем. XMLNS:префикс= «URI».
<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=»http://www.w3cschool.cc/furniture» >
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
В приведенном выше примере, атрибут XMLNS <таблица> тэг определяет час: префикс пространства имен квалифицированы: и е.
Когда пространство имен определено в начальном теге элемента, все дочерние элементы с одинаковым префиксом и связаны с пространством имен.
Пространство имен, вы можете объявить или они используются в элементе в корневой XML-элемент:
<root xmlns:h=»http://www.w3.org/TR/html4/»
xmlns:f=»http://www.w3cschool.cc/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>
Примечание: Пространство имен URI анализатор не будет использоваться для поиска информации.
Его цель состоит в том, чтобы дать пространству имен уникальное имя. Тем не менее, многие компании часто используют пространство имен как указатель, чтобы указать на фактическое существование страницы, эта страница содержит информацию о пространстве имен.
Посещение http://www.w3.org/TR/html4/ .
W3C парсеры для XML.
Проблемой при валидации (проверка правилоьности XML документа согласно схеме) является тот факт, что соответствие
документов их схемам некоторые броузеры не проверяют. В связи с этим возникает необходимость использовать
возможности DOM (Document Object Model — см. лаб.раб. №5) для проверки правильности. Функция валидации так или
иначе присутствует в любом парсере. Ее необходимо правильно вызвать. Проверить соответствие XDR схеме в ОС
Windows несколько легче, поскольку XML парсер от Microsoft является частью операционной системы. Достаточно
воспользоваться Java скриптом для проверке (как в прошлой лабораторной работе).
XSD является стандартом, поддерживаемым и развиваемым консорциумом W3C. В рамках этой поддержкиThe Apache Software Foundation создала набор ПО, представляющего
собой парсеры и другое обеспечение для работы с XML. Одним из таких
известных парсеров является Xerces. Он существует в
виде отдельного ПО, реализованного на С++ или Java. Чтобы не ограничивать Вас в выборе инструментальной среды и
ОС, будем использовать Java реализацию ввиду ее кроссплатформенности и простоты использования.
Замечание. Для запуска Java приложения необходимо, чтобы на компьютере была установлена Java
машина от Sun. Желательно с Java SDK.
Предположим у нас есть XML документ SONNET.XML
<?xml version="1.0"?> <sonnet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="sonnet.xsd" type="Shakespearean"> <author> <lastName>Shakespeare</lastName> <firstName>William</firstName> <nationality>British</nationality> <yearOfBirth>1564</yearOfBirth> <yearOfDeath>1616</yearOfDeath> </author> <title>Sonnet 130</title> <lines> <line>My mistress' eyes are nothing like the sun,</line> <line>Coral is far more red than her lips red.</line> <line>If snow be white, why then her breasts are dun,</line> <line>If hairs be wires, black wires grow on her head.</line> <line>I have seen roses damasked, red and white,</line> <line>But no such roses see I in her cheeks.</line> <line>And in some perfumes is there more delight</line> <line>Than in the breath that from my mistress reeks.</line> <line>I love to hear her speak, yet well I know</line> <line>That music hath a far more pleasing sound.</line> <line>I grant I never saw a goddess go,</line> <line>My mistress when she walks, treads on the ground.</line> <line>And yet, by Heaven, I think my love as rare</line> <line>As any she belied with false compare.</line> </lines> </sonnet>
И есть соответсвенно схема SONNET.XSD
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="sonnet"> <xsd:complexType> <xsd:sequence> <xsd:element ref="author"/> <xsd:element ref="title" minOccurs="0"/> <xsd:element ref="lines"/> </xsd:sequence> <xsd:attribute name="type" type="sonnetType" default="Shakespearean"/> </xsd:complexType> </xsd:element> <xsd:simpleType name="sonnetType"> <xsd:restriction base="xsd:string"> <xsd:enumeration value="Petrarchan"/> <xsd:enumeration value="Shakespearean"/> </xsd:restriction> </xsd:simpleType> <xsd:element name="author"> <xsd:complexType> <xsd:sequence> <xsd:element ref="lastName"/> <xsd:element ref="firstName"/> <xsd:element ref="nationality"/> <xsd:element ref="yearOfBirth" minOccurs="0"/> <xsd:element ref="yearOfDeath" minOccurs="0"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="lastName" type="xsd:string"/> <xsd:element name="firstName" type="xsd:string"/> <xsd:element name="nationality" type="xsd:string"/> <xsd:element name="yearOfBirth" type="xsd:string"/> <xsd:element name="yearOfDeath" type="xsd:string"/> <xsd:element name="title" type="xsd:string"/> <xsd:element name="lines"> <xsd:complexType> <xsd:sequence> <xsd:element ref="line" minOccurs="14" maxOccurs="14"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="line" type="xsd:string"/> </xsd:schema>
Готовый DomValidator для проверки правильности XML документа на Java можно скачать здесь.
Скомпилировать DOMValidator можно коммандой:
Проверить правильность SONNET.XML относительно схемы SONNET.XSD (должна находится в том же каталоге) можно
коммандой
И при необходимости сам Xerces можно скачать отсюда или с официального сайта.
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 <[email protected]>
- Dave Hollander, Contivo, Inc. <[email protected]>
- Andrew Layman, Microsoft <[email protected]>
- Richard Tobin, University of Edinburgh and Markup Technology Ltd <[email protected]>
- Henry S. Thompson, University of Edinburgh and W3C <[email protected]> — 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.
What is Namespace? Why is it necessary?
As an example, let’s assume we have an RDB with a table of the following structure (employeeTable, sectionTable). What kind of SQL statement would you create to obtain a list of Employee ID, Employee Department Name, and Employee Name? If we merged employeeTable and sectionTable with the secID column, then we would be able to obtain a list of employee IDs, employee departments and employee names. However, since the name column and secID column exist in both tables, we would have to designate the table name before the name and secID columns, or designate the alias of the table in order to clarify the table of the name and secID columns in question.
So, what happens when this data is expressed in an XML document? Let’s take two XML documents, and see how we can create a list showing employee ID, employee department and employee name using XML.
First, we will create a root element (employeeList element) and an element (personList element) to summarize employee information for one individual. You might have thought about creating an employee ID element (empID element in employeeXML document), department name element (name element in sectionXML document) and an employee name element (name element in employeeXML document) as child elements, but there’s a problem with this method. The problem is an «element name conflict.» The name element in the employee XML document is defined as an element representing the employee’s name, whereas the name element of the section XML document is defined as an element representing a department name. In merging these two XML documents, you will get a name element that has two separate meanings. While a human might be able to tell the difference between these two «name» elements and what they represent, computer systems cannot determine what these name elements are supposed to mean. The XML 1.0 specification never considered the merging of different types of XML documents (vocabularies) to create a new XML document, which led to this type of name conflict problem.
employeeXML Document
sectionXML Document
employeeListXML Document
The name element expressing employee name and the name element expressing department name conflict!
Namespace Declaration Scope
The namespace declaration scope is the scope for which the namespace prefix declared in a namespace declaration can be described. This scope covers the element and element content (from the element start tag to the end tag) for which the namespace declaration has been written. A namespace prefix can be written for an element or descendant element for which a namespace has been declared, or for an attribute defined therein.
A separate namespace declaration can be made for the descendant element of an element for which a namespace declaration has already been made, and a different namespace prefix within that scope can be used as well.
In addition to highest-order elements, namespace declarations can also be made in discrete sections. However, the same namespace declaration would have to be repeated many times, making the XML document difficult to follow. In this type of situation, it is best to make a collective set of namespace declarations in the highest-order element, as shown in the LIST1 example.
LIST1
Namespace Declaration
Write a namespace declaration according to the following description method, describing the element start tag:
If the element and/ or attribute belong to a namespace, a colon («:») is placed between the namespace prefix and the element name/ attribute name.
As a test, let’s take the previous employeeList XML document as an example, and provide a namespace declaration and an element belonging to the namespace.
<emp:employee xmlns:emp=»urn:corp:emp»>
<emp:personInfo>
…(omitted)…
</emp:personInfo>
</emp:employee>
In this example, we have declared the namespace prefix as «emp», and the namespace identifier (URI) as «urn:corp:emp». This means that element names and attribute names with the «emp» prefix (including the employee element) all belong to the urn:corp:emp namespace.
If the namespace prefix is not provided for an element and/ or attribute name, except for cases where a default namespace is declared (to be discussed later), the element name and/ or attribute name do not belong to a namespace. While the namespace declaration is described as a start tag attribute, this is different than a regular attribute. Elements having only an «xmlns:~» description have a namespace declaration, but no attribute.
Any arbitrary text string can be used as a namespace prefix; since there is no special meaning, any text string will do. However, the URI must be universally unique. Quite often a URL beginning with «http://~» is used in practice. Since the URL is not actually accessed, it is not a problem if the file, etc. does not really exist. Understand that a URI represents nothing more than a logical namespace name.
Default namespace declarations
A namespace declared by using the xmlns attribute on an element becomes the default
namespace for that element and all child elements contained within that element. This means any
such child element which does not have a namespace prefix or its own xmlns attribute will
be in the namespace of the containing element which had the xmlns declaration. Looking at this example:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/XSL/Format" > <xsl:output indent="yes" /> <xsl:strip-space elements="*" /> <xsl:template match="bookdata"> <root> <layout-master-set> <simple-page-master master-name="page-layout" page-height="11in" page-width="8in"> <region-body margin="1in" region-name="body" background-color="#dddddd" /> </simple-page-master> </layout-master-set> <page-sequence master-reference="page-layout"> <flow flow-name="body"> </flow> </page-sequence> </root> </xsl:template> </xsl:stylesheet>
The xsl:stylesheet element has xmlns=»http://www.w3.org/1999/XSL/Format», which establishes
«http://www.w3.org/1999/XSL/Format» as the default namespace for all child elements
of the xsl:stylesheet element. This means the <root> element on line 8 is in the
«http://www.w3.org/1999/XSL/Format» namespace, which Ibex recognises as the XSL FO namespace.
6 Applying Namespaces to Elements and Attributes
6.1 Namespace Scoping
The scope of a namespace declaration declaring a prefix extends from
the beginning of the start-tag in which it appears to the end of the
corresponding end-tag, excluding the scope of any inner declarations
with the same NSAttName part.
In the case of an empty tag, the scope is the tag itself.
Such a namespace declaration applies to all element and attribute
names within its scope whose prefix matches that specified in the
declaration.
The
corresponding to a prefixed element or attribute name has the
URI
to which the
is bound as its
,
and the
as its
.
<?xml version="1.0"?> <html:html xmlns:html='http://www.w3.org/1999/xhtml'> <html:head><html:title>Frobnostication</html:title></html:head> <html:body><html:p>Moved to <html:a href='http://frob.example.com'>here.</html:a></html:p></html:body> </html:html>
Multiple namespace prefixes can be declared as attributes of a single element,
as shown in this example:
<?xml version="1.0"?> <!-- both namespace prefixes are available throughout --> <bk:book xmlns:bk='urn:loc.gov:books' xmlns:isbn='urn:ISBN:0-395-36341-6'> <bk:title>Cheaper by the Dozen</bk:title> <isbn:number>1568491379</isbn:number> </bk:book>
6.2 Namespace Defaulting
The scope of a
declaration
extends from the beginning of the
start-tag in which it appears to the end of the corresponding end-tag,
excluding the scope of any inner default namespace declarations.
In the case of an empty tag, the scope is the tag itself.
A default namespace declaration applies to all unprefixed element names
within its scope.
Default namespace declarations do not apply directly to attribute names;
the interpretation of unprefixed attributes is
determined by the element on which they appear.
If there is a default namespace declaration in scope, the
corresponding to an unprefixed element name has the
URI
of the
as its
.
If there is no default namespace declaration in scope, the
namespace name has no value.
The namespace name for an unprefixed attribute name always has no value.
In all cases, the
is
(which is of course the same as the unprefixed name itself).
<?xml version="1.0"?> <!-- elements are in the HTML namespace, in this case by default --> <html xmlns='http://www.w3.org/1999/xhtml'> <head><title>Frobnostication</title></head> <body><p>Moved to <a href='http://frob.example.com'>here</a>.</p></body> </html>
<?xml version="1.0"?> <!-- unprefixed element types are from "books" --> <book xmlns='urn:loc.gov:books' xmlns:isbn='urn:ISBN:0-395-36341-6'> <title>Cheaper by the Dozen</title> <isbn:number>1568491379</isbn:number> </book>
A larger example of namespace scoping:
<?xml version="1.0"?> <!-- initially, the default namespace is "books" --> <book xmlns='urn:loc.gov:books' xmlns:isbn='urn:ISBN:0-395-36341-6'> <title>Cheaper by the Dozen</title> <isbn:number>1568491379</isbn:number> <notes> <!-- make HTML the default namespace for some commentary --> <p xmlns='http://www.w3.org/1999/xhtml'> This is a <i>funny</i> book! </p> </notes> </book>
The attribute value in a default namespace declaration
MAY
be empty.
This has the same
effect, within the scope of the declaration, of there being no default
namespace.
<?xml version='1.0'?> <Beers> <!-- the default namespace inside tables is that of HTML --> <table xmlns='http://www.w3.org/1999/xhtml'> <th><td>Name</td><td>Origin</td><td>Description</td></th> <tr> <!-- no default namespace inside table cells --> <td><brandName xmlns="">Huntsman</brandName></td> <td><origin xmlns="">Bath, UK</origin></td> <td> <details xmlns=""><class>Bitter</class><hop>Fuggles</hop> <pro>Wonderful hop, light alcohol, good summer beer</pro> <con>Fragile; excessive variance pub to pub</con> </details> </td> </tr> </table> </Beers>
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:
Пространства имен в реальном использовании
XSLT представляет собой язык, который может быть использован для преобразования XML-документов в другие форматы.
Документ XML ниже, представляет собой документ, используемый для преобразования XML в HTML.
Пространство имен «http://www.w3.org/1999/XSL/Transform» идентифицирует элементы XSLT внутри HTML — документа:
<?xml version=»1.0″ encoding=»UTF-8 » ?>
<xsl:stylesheet version=»1.0″
xmlns:xsl=»http://www.w3.org/1999/XSL/Transform»>
<xsl:template match=»/»>
<html>
<body>
<h2>My CD Collection</h2>
<table border=»1″>
<tr>
<th style=»text-align:left»>Title</th>
<th style=»text-align:left»>Artist</th>
</tr>
<xsl:for-each select=»catalog/cd»>
<tr>
<td><xsl:value-of select=»title»/></td>
<td><xsl:value-of select=»artist»/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Если вы хотите узнать больше о XSLT, пожалуйста , прочитайте наш XSLT Учебник .
❮ Предыдущая Следующая Глава ❯
Prefixed namespace declarations
Namespaces are usually declared at the top of an XSL stylesheet, as attributes of the xsl:stylesheet
element, like this:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" > </xsl:stylesheet>
The two namespace declarations above declare a namespace prefix (such as «xsl») and
associate this prefix with a namespace URI (i.e. «http://www.w3.org/1999/XSL/Transform»).
Once declared the prefix can be used in front of the name of any XML element
or attribute to show that this element is in the namespace associated with the prefix. The prefix
and the element name are separated by a ‘:’ like the xsl:template element shown here:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" > <xsl:template match="/"> </xsl:template> </xsl:stylesheet>
When an XSLT processor reads this stylesheet it creates a unique name
for this xsl:template element by associating the namespace URI and the
element name, so xsl:template internally becomes http://www.w3.org/1999/XSL/Transform:template.
The prefix
is just the mechanism for associating the element with the namespace, it does not form part of the element’s
unique name
.
When Ibex reads the results of an XSLT transformation, it looks for elements
in the namespace identified by the XSL FO URI («http://www.w3.org/1999/XSL/Format»), not elements with a prefix of «fo».
Any value can be used for a prefix. For example «xsl» is the commonly used prefix for the
«http://www.w3.org/1999/XSL/Transform» URI. But an example like the one below, which uses
«ss» as the prefix instead of «xsl» is still valid and will function just the same as
if «xsl» has been used as the prefix.
<?xml version="1.0" encoding="utf-8"?> <ss:stylesheet version="1.0" xmlns:ss="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" > <ss:template match="/"> </ss:template> </ss:stylesheet>
Whether to use the fo: prefix or not
If a default namespace is not used, then a prefix must be defined and used on each element. The XSL below
is functionally identical to the XSL above. In the XSL above the XSL FO namespace is declared as the
default namespace (by using xmlns=»http://www.w3.org/1999/XSL/Format»
on the xsl:template element), whereas in the XSL below there is no default namespace and the «fo» prefix
is used on all elements in the XSL FO namespace.
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <xsl:output indent="yes" /> <xsl:strip-space elements="*" /> <xsl:template match="bookdata"> <fo:root> <fo:layout-master-set> <fo:simple-page-master master-name="page-layout" page-height="11in" page-width="8in"> <fo:region-body margin="1in" region-name="body" background-color="#dddddd" /> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="page-layout"> <fo:flow flow-name="body"> </fo:flow> </fo:page-sequence> </fo:root> </xsl:template> </xsl:stylesheet>
Whether you use the fo: prefix or not is a matter of personal preference. There is no significant
performance difference either way. In the Ibex examples and the manual we use a default namespace
as this makes the examples clearer and easier to understand.
F Orphaned Productions (Non-Normative)
The following two productions are modified versions of ones which were present in the first two editions of this specification. They are no longer used, but are retained here to satisfy cross-references to undated versions of this specification.
Because the production of XML 1.0, originally used in the definition of , is no longer the correct basis for defining names since XML 1.0 Fifth Edition, the production has been modified to give the correct results against any edition of XML, by defining in terms of .
::= | |||
::= |
Note:
Production
takes advantage of the fact that a
single-character NCName is necessarily an NCNameStartChar, and
works by subtracting from the set of NCNames of all lengths the
set of all strings of two or more characters, leaving only the
NCNames which are one character long.
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.
Avoiding Element Name Conflicts
Perhaps some of you out there had the idea that element name conflicts can be avoided by applying the same type of alias used for RDB table merge explained above to an XML document. The W3C recommended a specification called «Namespaces in XML,» whereby XML vocabularies are mutually differentiated, allowing for the re-use of a vocabulary. Utilizing this XML namespace allows us to avoid any element name conflicts.
Here, we will add an XML namespace declaration and description in both the employee data XML document and section data XML document. Next, we will merge these two XML documents, and create a new employeeList data XML document. As a result, we can differentiate the «emp:name element» of the employeeList data XML document as an element representing employee name, and the «sec:name element» as an element representing department name. It might be easiest to think of one namespace as an aggregation of elements and attributes.
Employee XML Document
section XML Document
employeeList XML Document
Именование конфликты
В XML, имена элементов определяются разработчиком, когда два различных документа используют одинаковое имя элемента, конфликт имен будет происходить.
Этот XML несет в себе информацию таблицы HTML:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
Этот XML несет в себе информацию о таблице (предмет мебели):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
Если эти два XML-документы используются вместе, так как оба документа включены с различным содержанием и определение элемента <table>, называющие конфликты происходят.
XML-анализатор не может определить, как иметь дело с такими конфликтами.
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.