Now that you know the basics, this article explains how to use XML's more advanced constructs to author complex XML documents. Entities, namespaces, CDATA blocks, processing instructions - they're all in here, together with aliens, idiots, secret agents and buried treasure.
Setting up a namespace is simple - here's the syntax:
<elementName xmlns: prefix="namespaceURL">
In this case, the prefix is the unique string used to identify the namespace;
this is linked to a specific namespace URL.
A namsepace is usually declared at the root element level, although authors are free to declare it at a lower level of the tree structure too.
Once the namespace has been declared within the document, it can be used by prefixing each element within that namespace with the unique namespace identifier. Take a look at my revised stock portfolio, which now uses a "mytrades" namespace to avoid name clashes.
In case you're wondering, the namespace URL is simply a pointer to a Web address,
and is meaningless in practical terms; the XML specification doesn't really care where the URL points, or even if it's a valid link.
In case a single document contains two or more namespaces, adding namespace declarations and prefixes to every element can get kind of messy - as the following example demonstrates.
<?xml version="1.0"?>
<me:person xmlns:me="http://www.mywebsite.com/">
My
name is <me:name>Huey</me:name>. I'm <me:age>seven</me:age> years
old,
and I live in <me:address>Ducktown</me:address> with <rel:relationships
xmlns:rel="http://www.mywebsite.com/relationships/">my
brothers
<rel:name>Dewey</rel:name> and
<rel:name>Louie</rel:name></rel:relationships>.
</me:person>
In such a situation, XML allows you to specify any one namespace as the default
namespace, by omitting the prefix from the namespace declaration. Modifying the document above to make "me" the default namespace, we have
<?xml version="1.0"?>
<person xmlns="http://www.mywebsite.com/">
My name
is <name>Huey</name>. I'm <age>seven</age> years old, and I live in
<address>Ducktown</address>
with <rel:relationships
xmlns:rel="http://www.mywebsite.com/relationships/">my
brothers
<rel:name>Dewey</rel:name> and
<rel:name>Louie</rel:name></rel:relationships>.
</person>
Namespaces need not be restricted to elements alone - attributes can use namespaces
too, as the following example demonstrates.
<?xml version="1.0"?>
<mystuff:collection xmlns:mystuff="http://www.somedomain.com/mystuff"
xmlns:music="http://www.somedomain.com/music_genres">
<mystuff:artist>Spears,
Britney</mystuff:artist>
<mystuff:title music:genre="Pop">Oops, I Did It
Again!</mystuff:title>
</mystuff:collection>
This article copyright Melonfire 2001. All rights reserved.