[jdom-interest] How do I use namespaces?

Jason Hunter jhunter at xquery.com
Wed Feb 4 16:11:44 PST 2004

Garey Mills wrote:

> Hi - 
> 	I am using JDOM to parse documents that use attributes in a number
> of different namespaces. The namespaces correspond to standards that are
> being revised, so I can't be sure what their URI is (since each revision
> is given a new URI).
> 	The namespaces are declared in the root element, for example:
> xmlns:mets="http://www.loc.gov/METS/"
> xmlns:moa2="http://sunsite.berkeley.edu/MOA2/"
> xmlns:mods="http://www.loc.gov/mods/v3" 
> xmlns:mix="http://www.loc.gov/mix/"
> xmlns:xlink="http://www.w3.org/TR/xlink"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> 	If, at some point in the document, I want to retrieve an attribute
> that belongs to, say, the 'mods' namespace, can I just use the prefix?

No, you can't substitute a prefix for a namespace because there is no 
guaranteed one-to-one mapping of prefix and URI.  The same prefix could 
be bound to different URIs depending on your location in the document.

> 	Attribute x = myElement.getAttribute("x", "mods");
> 	I don't think I can because getAttribute needs a Namespace and not
> a string
> 	So do I have to do something more convoluted, such as retrieve the
> namespaces defined on the element, search for the one with the name "mods"
> and then include that one in the get Attribute call?
> 	Or is there someway I can access the namespaces declared in the
> root element?

elt.getNamespace(String prefix) returns the NS in scope for that prefix.


More information about the jdom-interest mailing list