Skip to content

JAXB2 Namespace Prefix Plugin

Laurent Schoelens edited this page Jan 15, 2024 · 5 revisions

Namespace Prefix Plugin

This plugin adds :

  • javax.xml.bind.annotation.XmlNs annotations to package-info.java files for JAXB2.
  • jakarta.xml.bind.annotation.XmlNs annotations to package-info.java files for JAXB 3+.

Those annotations tells Jaxb to generate XML schema's instances with specific namespaces prefixes, instead of the auto-generated (ns1, ns2, ...) prefixes. Definition of thoses prefixes is done in the bindings.xml file.

Activation

The plugin is activated by the -Xnamespace-prefix

Example of binding XML file

<?xml version="1.0"?>
<jxb:bindings version="3.0"
  xmlns:jxb="https://jakarta.ee/xml/ns/jaxb"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:namespace="http://jaxb2-commons.dev.java.net/basic/namespace-prefix">

  <jxb:bindings schemaLocation="unireg-common-1.xsd">
    <jxb:schemaBindings>
      <jxb:package name="ch.vd.unireg.xml.common.v1" />
    </jxb:schemaBindings>
    <jxb:bindings>
      <namespace:prefix name="common-1" />
    </jxb:bindings>
  </jxb:bindings>

</jxb:bindings>

Starting from 4.0.1 version of the plugin (see #457), you can also define extra binding prefix by providing the namespaceURI argument as parameter.
Defining namespaceURI as the targetNamespace will make the plugin run as attribute was undefined.

Example of binding XML file with extra namespace-prefix bindings

<?xml version="1.0"?>
<jxb:bindings version="3.0"
  xmlns:jxb="https://jakarta.ee/xml/ns/jaxb"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:namespace="urn:jaxb.jvnet.org:plugin:namespace-prefix">

  <jxb:bindings schemaLocation="unireg-common-1.xsd">
    <jxb:schemaBindings>
      <jxb:package name="ch.vd.unireg.xml.common.v1" />
    </jxb:schemaBindings>
    <jxb:bindings>
      <namespace:prefix name="common-1" />
      <namespace:prefix name="other" namespaceURI="anotherNamespaceURI" />
    </jxb:bindings>
  </jxb:bindings>

</jxb:bindings>

This will generate the following annotations on the package-info.java file, if targetNamespaceOfCommon1 is the targetNamespace of the unireg-common-1.xsd XSD

    @XmlNs(namespaceURI = "targetNamespaceOfCommon1", prefix = "common-1"),
    @XmlNs(namespaceURI = "anotherNamespaceURI", prefix = "other")
Clone this wiki locally