Stephen's dev blog

Posts Tagged ‘namespaces

  • In: Tutorials
  • Comments Off on XML namespaces

If you’re a developer, I’m sure you would have seen XML namespaces somewhere before whilst looking at an XML document. But what are they? According to the Wiki page:

“XML namespaces are used for providing uniquely named elements and attributes in an XML instance. They are defined by a W3C recommendation called Namespaces in XML. An XML instance may contain element or attribute names from more than one XML vocabulary. If each vocabulary is given a namespace then the ambiguity between identically named elements or attributes can be resolved.”

So they provide a way of differentiating between similar, or same named XML elements/attributes in an XML document. How do you use them? Here’s an example:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns:prod="http://www.my-site.com/namespaces/product" xmlns:ship="http://www.my-site.com/namespaces/shipping">
    <prod:items>
        <prod:item>
            <prod:name value="My product" />
            <prod:code value="123321" />
            <prod:price prod:currency="GBP" value="11.99" />
        </prod:item>
    </prod:items>
    <ship:method ship:postCode="CR3 4FT">
        <ship:name value="Next day AM" />
        <ship:price ship:currency="GBP" value="3.99" />
    </ship:method>
</root>

The first thing you’ll probably notice is the use of the xmlns attributes of the root node. This is used to declare a namespace. It can be used on any node and only child nodes of a node with the xmlns attribute will be able to use that namespace.

The part after the colon – in one of our cases ‘prod’ – is the alias for the namespace. All elements and attributes of that namespace have to be prefixed with this alias. The URL that the xmlns attribute points to doesn’t actually have to contain anything, it doesn’t even really have to exist. Your standard browser XML parser doesn’t take any information from this URL, it’s just there for usability. Some people use this URL to give information on what the namespace in question is used for and what it’s attributes/elements are. Oh, and it can’t be an empty string (“”)!



  • Patrick: I changed my code, but now I have another problem: Fatal error: Call to a member function isAvailable() on a non-object in /var/www/vhost/web/shopA
  • Stephen Gray: Hi Patrick, That first error is my fault. I had the method name for the refund() method as void() as I had copied the code from the other method!
  • Patrick: Hi Stephen, thanks for sharing your knowledge about creating a custom payment module. I need an extension for magento to handle a credit card payme

Categories