乐闻世界logo
搜索文章和话题

What is XML Namespace and how do you declare and use it?

2月21日 14:23

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:

  • xmlns is a reserved attribute used to declare a namespace
  • prefix is the namespace prefix (optional, default namespace doesn't need a prefix)
  • namespaceURI is 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

  1. Use unique URIs: Namespace URIs should be unique, typically using URL format
  2. Choose meaningful prefixes: Prefixes should be short and easy to understand
  3. Avoid overuse: Only use namespaces when necessary
  4. 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.

标签:XML