XML Namespace Reminds OOPs Namespace

XML namespaces are used for providing uniquely named elements and attributes in an XML document. An XML instance may contain element or attribute names from more than one XML vocabulary. If each vocabulary is given a namespace, the ambiguity between identically named elements or attributes can be resolved.

A namespace name is a uniform resource identifier (URI). Typically, the URI chosen for the namespace of a given XML vocabulary describes a resource under the control of the author or organization defining the vocabulary, such as a URL for the author’s Web server. However, the namespace specification does not require nor suggest that the namespace URI be used to retrieve information; it is simply treated by an XML parser as a string. For example, the document at http://www.w3.org/1999/xhtml itself does not contain any code. It simply describes the XHTML namespace to human readers. Using a URI (such as “http://www.w3.org/1999/xhtml”) to identify a namespace, rather than a simple string (such as “xhtml”), reduces the probability of different namespaces using duplicate identifiers.

Ref: http://en.wikipedia.org/wiki/XML_namespace

Without futher ado let’s understand with simple example

XML (test.xml)
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet type="text/xsl" href="test.xslt"?>
<root xmlns:h1="http://www.w3.org/h1" xmlns:h2="http://www.w3.org/h2" >
    <two h1:attr="h1_attr1" h2:attr="h2_attr1">H1 Test</two>
    <two  h1:attr="h1_attr2" h2:attr="h2_attr2">H2 Test</two>
XSLT (test.xslt) 
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:h1="http://www.w3.org/h1" xmlns:h2="http://www.w3.org/h2">
  <xsl:output  method="xml" indent="yes" />
  <xsl:template match="/">
      <xsl:apply-templates />

  <!-- Template / Function (Easy Understanding -->
  <xsl:template match="h1:one">
      <xsl:apply-templates select="two" />
  <xsl:template match="h2:one">
      <xsl:apply-templates select="two" />
  <xsl:template match="two">
    <xsl:attribute name="h1:attr">
      <xsl:value-of select="@h1:attr" />
    <xsl:attribute name="h2:attr">
      <xsl:value-of select="@h2:attr" />
    <xsl:value-of select="."/>
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:h1="http://www.w3.org/h1" xmlns:h2="http://www.w3.org/h2">
  <test attr="h1_attr1">H1 Test</test>
  <test attr="h1_attr2">H2 Test</test>

Note:  How apply-templates processes XML Document Very Interesting !!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s