Open In App

XML Namespaces

XML namespaces prevent naming conflicts between elements and attributes in XML documents, especially when various XML vocabularies are joined or elements with the same name come from different sources.

Default Namespace Declaration

Default Namespace Declaration in XML namespaces assigns a default namespace to all unprefixed components inside a given scope. This signifies that elements without a prefix are presumed from the given namespace. The "xmlns" element is used to declare the default namespace.

Syntax:

<root xmlns="http://example.com/ns">
<child>Content</child>
</root>

Example: To demonstrate the XML library catalog file structure in XML.

<?xml version="1.0" encoding="UTF-8"?>
<library
    xmlns="http://example.com/library">
    <book>
        <title>XML Basics</title>
        <author>John Doe</author>
    </book>
    <book>
        <title>Advanced XML</title>
        <author>Jane Smith</author>
    </book>
</library>

Output:

Screenshot-2024-04-10-162410

Prefixed Namespace Declaration

In XML namespaces, the Prefixed Namespace Declaration method assigns a prefix to a namespace URI. This allows elements and attributes from that namespace to be identified with the specified prefix. Prefixed namespaces are especially beneficial when items from different namespaces appear in the same XML document.

Syntax:

<root xmlns:prefix="http://example.com/ns">
<prefix:child>Content</prefix:child>
</root>

Example: To demonsrtate the books catalog file structure in XML.

<?xml version="1.0" encoding="UTF-8"?>
<catalog
    xmlns:bk="http://example.com/books"
    xmlns:auth="http://example.com/authors">
    <bk:book>
        <bk:title>XML Basics</bk:title>
        <auth:author>John Doe</auth:author>
    </bk:book>
    <bk:book>
        <bk:title>Advanced XML</bk:title>
        <auth:author>Jane Smith</auth:author>
    </bk:book>
</catalog>

Output:

Screenshot-2024-04-10-162909

Article Tags :