Welcome to CodeYourCraft's XML Namespaces tutorial! In this lesson, we'll dive into the world of XML Namespaces, a powerful tool that helps avoid naming conflicts and simplifies the integration of various XML vocabularies.
XML Namespaces are a way to qualify element and attribute names in an XML document to uniquely identify their source. This allows multiple XML vocabularies to coexist within a single document without conflicts.
An XML Namespace is identified by a Unique Identifier (URI), which can be any valid URI, even if it doesn't resolve to anything. It's important to note that URIs are used solely for identification purposes and do not need to be accessible.
<prefix:element URI="http://example.com/namespace">...</prefix:element>š” Pro Tip: Prefixes are usually abbreviations of the corresponding Namespace URI.
An XML Namespace can be declared at three different scopes:
To declare a Namespace at the document level, use the xmlns attribute on the root element:
<root xmlns:prefix="http://example.com/namespace">
<!-- All child elements of root with the prefix: prefix prefix will belong to the specified Namespace -->
<prefix:element>...</prefix:element>
</root>To declare a Namespace at the element level, use the xmlns attribute on the specific element:
<root>
<prefix:element xmlns:prefix="http://example.com/namespace">...</prefix:element>
</root>To declare a Namespace at the attribute level, use the xmlns:prefix attribute on the specific attribute:
<root>
<element attribute:prefix="http://example.com/namespace" />
</root>š” Pro Tip: When declaring Namespaces, choose short and meaningful prefixes to make your XML documents more readable.
To qualify elements and attributes with their corresponding Namespace, use the prefix followed by a colon (:) before the element or attribute name:
<root xmlns:prefix="http://example.com/namespace">
<prefix:element>...</prefix:element>
<standard:element standard:attribute="value"/>
</root>If two or more Namespaces have the same prefix, it may lead to colliding Namespaces. To resolve this issue, use different prefixes for each Namespace:
<root xmlns:ns1="http://example1.com/namespace" xmlns:ns2="http://example2.com/namespace">
<ns1:element1>...</ns1:element1>
<ns2:element2>...</ns2:element2>
</root>Which of the following is a valid XML Namespace declaration at the element level?