A namespace allows you to identify elements and attributes in an XML document.
Namespaces are useful when the XML document contains data from different domains or languages.
In particular, namespaces can be used to distinguish between tags with the same name that belong to different domains or languages.
For example, an XML document may contain
tags from the XSLT language (
stylesheet
,
template
)
as well as tags from HTML (
html
,
body
):
<stylesheet>
<template match="/">
<html>
<body>
<apply-templates />
</body>
</html>
</template>
</stylesheet>
A namespace is identified by a prefix (alias).
This alias can be used to qualify a tag or attribute and mark it as belonging to a specific namespace.
Tags and attributes are associated with a namespace by prefixing their names with the alias, followed by a colon "
:
":
<xsl:stylesheet>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
But before using a namespace alias, it must be declared.
For example, to declare a namespace for the alias "xsl", you associate this alias with a value
(by prefixing it with the keyword "
xmlns
" followed by a colon):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The alias name can be any valid string; there is no strict naming convention, except that it must be a valid name (see tag naming rules).
So the alias "xsl" can be replaced with "myxsl" or any other valid name.
If an alias is used to qualify an element, then it must be used in both the opening and closing tags of that element.
If an element has no alias (for example, "<html>"), then it does not belong to any namespace
(unless a default namespace is defined — see the next section).
Note that a namespace only applies to the element where it is defined and its descendant elements.