Easy Tutorial
❮ Xml To Html Xml Dom Advanced ❯

XML Namespaces


XML namespaces provide a method to avoid element naming conflicts.


Naming Conflicts

In XML, element names are defined by the developer, and when two different documents use the same element name, a naming conflict occurs.

This XML carries information about an HTML table:

This XML document carries information about a table (a piece of furniture):

If these two XML documents are used together, a naming conflict occurs because both documents contain <table> elements with different content and definitions.

The XML parser cannot determine how to handle such conflicts.


Avoiding Naming Conflicts with Prefixes

Naming conflicts in XML can be easily avoided by using name prefixes.

This XML carries information about an HTML table and a piece of furniture:

In the above example, there will be no conflict because the two <table> elements have different names.


XML Namespaces - xmlns Attribute

When prefixes are used in XML, a so-called namespace for the prefix must be defined.

The namespace is defined in the xmlns attribute of the element's start tag.

The syntax for namespace declaration is as follows: xmlns:*prefix* ="*URI*".

In the above example, the xmlns attribute of the <table> tag defines the qualified namespaces for the h: and f: prefixes.

When a namespace is defined in the start tag of an element, all child elements with the same prefix are associated with the same namespace.

Namespaces can be declared in the element where they are used or in the root element of the XML:

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

Its purpose is to give the namespace a unique name. However, many companies often use the namespace as a pointer to an actual web page that contains information about the namespace.

Please visit http://www.w3.org/TR/html4/.


Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters that identifies an Internet resource.

The most commonly used URI is the Uniform Resource Locator (URL) that identifies an Internet domain address. Another less commonly used URI is the Uniform Resource Name (URN).

In our examples, we only use URLs.


Default Namespace

Defining a default namespace for an element can save us the work of using prefixes in all child elements. Its syntax is as follows:

This XML carries information about an HTML table:

This XML carries information about a piece of furniture:


Practical Use of Namespaces

XSLT is an XML language used to transform XML documents into other formats, such as HTML.

In the following XSLT document, you can see that most of the tags are HTML tags.

Non-HTML tags have the prefix xsl and are identified by this namespace: xmlns:xsl="http://www.w3.org/1999/XSL/Transform".

If you want to learn more about XSLT, please find our XSLT tutorial on our homepage.

❮ Xml To Html Xml Dom Advanced ❯