XML Namespace is a mechanism in XML used to resolve element and attribute name conflicts. When multiple XML documents or schemas are merged, elements with the same name may represent different meanings. Namespaces solve this problem by adding unique identifiers to elements and attributes.
Namespace Declaration
Namespaces are declared using the xmlns attribute, with the syntax:
xml<root xmlns:prefix="namespaceURI"> <prefix:element>content</prefix:element> </root>
Where:
xmlnsis a reserved attribute used to declare a namespaceprefixis the namespace prefix (optional, default namespace doesn't need a prefix)namespaceURIis the unique identifier of the namespace (usually a URL)
Types of Namespaces
1. Default Namespace
xml<root xmlns="http://example.com/ns"> <element>content</element> </root>
The default namespace applies to the current element and all its unprefixed child elements.
2. Prefixed Namespace
xml<root xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:schema>...</xs:schema> </root>
A prefixed namespace only applies to elements and attributes using that prefix.
Namespace Scope
- Namespace declarations are valid in the element where they are declared and all its descendant elements
- Child elements can override parent element namespace declarations
- Elements without a declared namespace belong to "no namespace"
Namespace Best Practices
- Use unique URIs: Namespace URIs should be unique, typically using URL format
- Choose meaningful prefixes: Prefixes should be short and easy to understand
- Avoid overuse: Only use namespaces when necessary
- Maintain consistency: Use the same namespace declarations throughout the document
Practical Application Example
xml<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:m="http://www.example.com/stock"> <soap:Header> <m:Authentication> <m:Username>user</m:Username> <m:Password>pass</m:Password> </m:Authentication> </soap:Header> <soap:Body> <m:GetStockPrice> <m:StockSymbol>IBM</m:StockSymbol> </m:GetStockPrice> </soap:Body> </soap:Envelope>
In this example, the soap prefix is used for SOAP protocol elements, and the m prefix is used for custom business logic elements, with no interference between the two.