Namespaces
Purpose Namespaces were added late to the XML specification They serve two purposes To distinguish between elements and attributes of different vocabularies To group all related elements and attributes from an XML application so a software application can easily recognize them
Namespace Functions c:address c:customerid e:dept e:salary e:hiredate xmlns:e=“http://employee” xmlns:c=”http://customer” c:address c:customerid e:name c:name c:phone e:phone e:dept e:salary e:hiredate Group related objects Distinguish vocabularies
Default Namespace You can use the xmlns attribute to declare a default namespace <elementname xmlns=“URI”> The URI (universal Resource Identifier) can be a name or address that identifies a resource. Typically the URI is a web address, however this address does not need to point to any actual document
Default Namespace Example <?xml version=“1.0” encoding=“UTF-8” ?> <employees xmlns=“http://seattlecentral.org/faculty/sconge/employees.xsd”> . . . </employees>
Namespaces with Prefixes You can assign a prefix to a namespace <emp:employees xmlns:emp=“http://seattlecentral.org/facutly/sconge/employees.xsd”> <emp:employee> <emp:firstname>Alice</emp:firstname> . . . </emp:employee> </emp:employees>
Using Multiple Namespaces A single XML document can contain multiple namespaces You can nest default namespaces or differentiate them by prefixes
Nesting Namespaces <employees xmlns=“http://seattlecentral.org/facutly/sconge/employee.xsd”> <employee> <firstname>Alice</firstname> <lastname>Smith</lastname> <payroll xmlns=“http://seattlecentral.org/faculty/sconge/payroll.xsd”> <status>Full time</status> <paytype>Salary</paytype> <paystep>5</paystep> </payroll> <dept>IT</dept> </employee> </employees>
Attributes The default namespace does not include the attributes Attributes can include a namespace prefix By default the attribute belongs to the element’s private namespace
Namespaces Best Practices Use the default namespace on the root element Use one default namespace at most Declare prefixed namespaces as soon as possible Do not use the same prefix for different name spaces Use one prefix for each namespace