XML

Namespace Prefixes

Let's begin our examination of namespaces by looking at prefixes. Each namespace has a prefix that is used as a reference to the namespace. This prefix must follow all the usual naming conventions for XML names as we discussed in Chapter 3. In addition, prefixes must not begin with xmlns or xml. You can't use xmlns because it's the keyword that's used to define a namespace, and xml can't be used because it's the processing instruction used to define attributes of an XML document.

Namespaces are declared within an element's begin tag. The syntax for declaring a namespace looks like this:

  <namespacePrefix:elementName xmlns:namespacePrefix = 'URL'>

This particular URL does not refer to a DTD or a schema. The URL doesn't even have to point to an existing file. Its purpose is to provide a unique name to associate with the elements and attributes in the XML document. The namespace can also be identified by a URI or a URN.

Because each URL, URI, or URN is unique, using a company's URL followed by additional text should create unique identifiers for each namespace. Here is an example of this format:

  <?xml version="1.0"?>
  <bill:message xmlns:bill='http://www.northwindtraders.com/bill'>
     <bill:date>1/1/2002</bill:date>
     <bill:body>Your current balance is $1,999,999.00. Please pay
        immediately. Thank you.</bill:body>
  </bill:message>

You can also declare more than one namespace in an element's begin tag, as shown here:

  <?xml version="1.0"?>
  <bill:message xmlns:bill='http://www.northwindtraders.com/bill'
     xmlns:body='http://www.northwindtraders.com/message'>
     <bill:date>1/1/2002</bill:date>
     <body:body>Your current balance is $1,999,999.00. Please pay
        immediately. Thank you. </body:body>
  </bill:message>

In this example, the message element contains two namespace declarations: bill and body. The bill namespace is used to define the message element and the date child element. The body namespace is used to define the body child element.

by BrainBellupdated
Advertisement: