Understanding XML Namespaces

Default Namespace

If most of the elements in the document belong to the same namespace, it is not necessary to prefix each element name. Instead you can define a default namespace that applies to all non-prefixed elements and attributes. The syntax for defining a default namespace is xmlns=”namespace”. For example, if you define the HR namespace as the default namespace, the document becomes easier to read:

<employees xmlns="http://www.devxpert.com/schemas/hr/"
xmlns:py="http://www.devxpert.com/schemas/payroll/">
<employee>
    <id>49982</id>
    <name>Bart Simpson</name>
    <hireDate>2000-07-04</hireDate>
    <py:salary>4000765.00</py:salary>
    <py:taxes>3980765.27</py:taxes>
</employee>
<employee>
    <id>12345</id>
    <name>Hugo Simpson</name>
    <hireDate>2000-05-29</hireDate>
    <py:salary>82000.00</py:salary>
    <py:taxes>16567.87</py:taxes>    
</employee>
</employees>

The default namespace applies to the element on which it was defined and all descendants of that element. If one of the descendants has another default namespace defined on it, this new namespace definition overrides the previous one and becomes the default for that element and all its descendants. For example, in the following document the default namespace for the <salary> element (and its descendants if it had any) is http://www.developerfusion.com/schemas/payroll/:

<employees xmlns="http://www.devxpert.com/schemas/hr/"
xmlns:py="http://www.devxpert.com/schemas/payroll/">
<employee>
    <id>49982</id>
    <name>Bart Simpson</name>
    <hireDate>2000-07-04</hireDate>
    <salary
xmlns="http://www.devxpert.com/schemas/payroll/”>
4000765.00
</salary>
    <py:taxes>3980765.27</py:taxes>
</employee>
</employees>

You might also like...

Comments

About the author

Yasser Shohoud United States

Yasser started programming at the age of 12 when he wrote his first text-based game on a Commodore PET. He's since moved to IBM mainframes then to Microsoft technologies and has worked as System...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The difference between theory and practice is smaller in theory than in practice.”