Using Multiple Namespaces in a Document

Namespaces remove ambiguity from element type names. This assists the exchange of XML documents between users, but it also allows elements from different namespaces—in context implicitly different XML application languages—to be mixed in the same document.

You can mix elements in the same document if you understand the scope of namespaces.

Scope of Namespaces

The scope of a namespace is limited to all elements nested inside the element on which the namespace was declared. However, the namespace may be altered by a namespace declaration on any of the nested elements.

Look at a simple example:

<somePrefix:anElement xmlns:somePrefix= 
  http://www.XMML.com/someNamespace> 
 <anotherPrefix:anElement 
  xmlns:anotherPrefix="http://www.XMML.com/anotherNamespace> 
  Some content 
 </anotherPrefix:anElement> 
</somePrefix:anElement> 

The somePrefix:anElement element has an anotherPrefix:anElement element nested inside it. The somePrefix:anElement element is associated with the namespace URI http://www.XMML.com/someNamespace. The namespace declaration on the anotherPrefix:anElement element associates the anotherPrefix namespace prefix with a different namespace URI: http://www.XMML.com/anotherNamespace.

Let’s return to the earlier example and explore how order elements from different namespaces might be used in a single XML document.

You might have a document with a structure similar to the following from a police department to a supplier:

<PurchaseOrder 
xmlns="http://MyWonderfulLocalPoliceDepartment.com/ 
  purchaseOrders"> 
<Reason> 
<order> 
 <Location>Seattle</Location> 
 <Description>A riot lasted several hours following clashes 
   with anti-globalization protesters. 
</order> 
</Reason> 
<Supplier> 
<business:order 
  xmlns:business="http://SomeFriendlyLocalBusiness.com/ 
   PurchaseOrders"> 
 <business:orderNumber> 
  AB123 
 </business:orderNumber> 
 <business:Items> 
  <business:Item number="20">Tear Gas Cartridges 
   </business:Item> 
  <business:Item number="10">Personal Protection Masks 
    </business:Item> 
 </business:Items> 
</business:order> 
</Supplier> 
<PurchaseOrder> 

Two namespace declarations exist. The first associates the default namespace with the namespace URI http://MyWonderfulLocalPoliceDepartment.com/purchaseOrders. The second, on the business:order element, associates the business namespace prefix with the namespace URI http://SomeFriendlyLocalBusiness.com/PurchaseOrders. You can clearly distinguish the order element in the default namespace from the business:order element. The XML processor uses the namespace URIs rather than the namespace prefixes to distinguish the namespaces.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset