Pages

January 29, 2013

JAXB: use namespaces

Problem:
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.

Solution:
One proposed solution is to use NamespacePrefixMapper


final Marshaller marshaller = JAXBContext.newInstance(MyObjectFactory.class)
    .createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
  new NamespacePrefixMapper() {
      @Override
      public String[] getPreDeclaredNamespaceUris() {
        return new String[] { MY_NAMESPACE };
      }
      @Override
      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="http://www.w3.org/2001/XMLSchema" 
       targetNamespace="http://www.w3.org/1999/XSL/Transform"
        xmlns:tns="http://www.w3.org/1999/XSL/Transform" 
      elementFormDefault="qualified" 
      xmlns:s="http://www.w3.org/2000/sss">
  <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="http://www.w3.org/2000/sss". Which is util for xsl.
So the usefulness of this article

1 comment: