January 29, 2013

JAXB: use namespaces

I want to use jaxb to generate a xsl file from xsd file.
The xsd file contains, in addition to the default namespace (DEFAULT_NAMESPACE), another namespace (MY_NAMESPACE) which is not used in xsd but it will be used in the xsl.
The generator does not copy MY_NAMESPACE, so the xsl file is no longer valid.

One proposed solution is to use NamespacePrefixMapper

final Marshaller marshaller = JAXBContext.newInstance(MyObjectFactory.class)
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  new NamespacePrefixMapper() {
      public String[] getPreDeclaredNamespaceUris() {
        return new String[] { MY_NAMESPACE };
      public String getPreferredPrefix(final String namespaceUri,
        final String suggestion, final boolean requirePrefix) {
        if (namespaceUri.equals(MY_NAMESPACE)) {
           return MY_NAMESPACE_PREFIX;
        return suggestion;

Xsd example:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="" 
  <xs:element name="stylesheet" type="tns:Stylesheet"></xs:element>
     <xs:complexType name="Stylesheet">
    <xs:attribute name="name" type="xs:string"></xs:attribute>
    <xs:attribute name="select" type="xs:string"></xs:attribute>
  </xs:complexType> </xs:schema>

when I use jaxb to generate xsl, I do not get the namespace xmlns:s="". Which is util for xsl.
So the usefulness of this article

1 comment: