Skip to main content

namespace information in marshaled XML:

4 replies [Last post]
grunge
Offline
Joined: 2005-10-12

What annotations are available to affect namespaces when marshaling to XML? For example, I want to have the xmlns and xsi:schemaLocation information automatically written in my XML instance documents when marshaling.

On the schema side, when generating the schema with the schemagen tool, @XmlType(namespace=...) (or a package level @XmlSchema) nicely causes "targetNamespace" information to be put into the resulting schema.

However, on the instance side, I am unable to cause namespace information to be outputed when marshaling. (I've seen the jaxb.schemaLocation property that JAXB providers are apparently supposed to support, however, I've haven't been able to make this work (with EA2)).

How do people normally put xmlns and xsi:schemaLocation into their instance documents?

Thanks.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
grunge
Offline
Joined: 2005-10-12

Ok, I've finally figured this out.

It turns out that I had a few deeply nested nodes that were not given namespace declarations (therefore, they were in no namespace), therefore a top-level default namespace technically could not be applied. When I declared the namespace on the nested nodes as well, the marshaler could then do the right think by putting a default namespace on the top node.

grunge
Offline
Joined: 2005-10-12

Next, I've tried implementing NamespacePrefixMapper. However, when I return "" from getPreferredPrefix() which is supposed to indicate to use the default namespace, it uses a generated "ns2" instead. If I return a real prefix (ie: "r"), it will use that just fine. It just will not use the default namespace (ie: xmlns="http://foobar").

Does no one want to marshal documents that use the default namespace, or am I missing something?

grunge
Offline
Joined: 2005-10-12

I should also mention that I have tried the "namespace" attributes of the many @Xml... annotations with no success. Essentially my question is simply, how can I produce an xmlns="http://namespace/foobar" for a given element?

grunge
Offline
Joined: 2005-10-12

Ok, I am half way there. The "jaxb.schemaLocation" property does in fact work.

ie:
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://namespace/foobar foobar.xsd");

This takes care of the xsi:schemaLocation output, however, I still need the output XML to include an appropriate "xmlns" declaration.