- Java xml namespace prefix
- Second, the statement prefixed namespace
- Third, the generation and the namespace prefix of a prefix node generated
- Fourth, supplement
- JAXB Customized Namespace Prefixes Example using NamespacePrefixMapper
- Dependencies
- NamespacePrefixMapper
- Configure
- Spring’s Jaxb2Marshaller
- Java’s Marshaller
- Saved searches
- Use saved searches to filter your results more quickly
- License
- Siggen/jaxb2-namespace-prefix
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Java XML and JSON Binding
- Pages
- November 30, 2011
- JAXB and Namespace Prefixes
Java xml namespace prefix
/** * Entity */ @XmlRootElement(name="Order", namespace="http://www.xl.com.cn/msg") public class Order
Second, the statement prefixed namespace
/** * package-info.java * On the same entity and a packet path */ @XmlSchema( xmlns= < @XmlNs(prefix="xsi", namespaceURI="http://www.w3.org/2001/XMLSchema-instance"), >) package cn.com.xl.entity; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlSchema;
/** * Entity */ @XmlRootElement(name="Order") public class Order
Third, the generation and the namespace prefix of a prefix node generated
/** * package-info.java * On the same entity and a packet path */ @XmlSchema( xmlns= < @XmlNs(prefix="msg", namespaceURI="http://www.xl.com.cn/msg") >) package cn.com.xl.entity; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlSchema;
/** * Entity */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="Order", namespace="http://www.xl.com.cn/msg") public class Order < @XmlElement(name="OrderId", namespace="http://www.xl.com.cn/msg") private String OrderId; >
Fourth, supplement
1、A child node of the prefix is not required, when namespace entity is not provided for the field can be annotated @XmlElement
2、Require multiple namespaces, which can add multiple @XmlNs in the package-info
3、namespace prefix necessary annotated as configured nodes configured in a statement in the package-info, otherwise the node prefixes will nsN format
JAXB Customized Namespace Prefixes Example using NamespacePrefixMapper
Do you need to specify what namespace prefixes are used in your JAXB marshaled XML? For example, do you want to see
If you are using the default JAXB implementation provided with Java 6 or later, you can configure the namespace prefixes by extending the NamespacePrefixMapper and setting a property to tell the marshaller to use your extension.
For more details on marshalling JAXB objects to XML, review this previous JAXB tutorial on Marshalling and Unmarshalling.
Dependencies
Since you need to extend a class that is defined in the JAXB API’s Reference Implemenation (RI), you must pull it in as a dependency.
You can download the libraries directly from jaxb.java.net, or you can add the Maven dependencies.
com.sun.xml.bind jaxb-impl 2.2.11 com.sun.xml.bind jaxb-core 2.2.11
NamespacePrefixMapper
Once you have the JAXB libraries, you can extend the com.sun.xml.bind.marshaller.NamespacePrefixMapper class. This is the core class that provides the mapping of XML namespaces to the desired prefix.
Sample extension (using Java 8 syntax)
package com.intertech; import java.util.HashMap; import java.util.Map; import com.sun.xml.bind.marshaller.NamespacePrefixMapper; /** * Implementation of that maps the schema * namespaces more to readable names. Used by the jaxb marshaller. Requires * setting the property "com.sun.xml.bind.namespacePrefixMapper" to an instance * of this class. ** Requires dependency on JAXB implementation jars *
*/ public class DefaultNamespacePrefixMapper extends NamespacePrefixMapper < private MapnamespaceMap = new HashMap<>(); /** * Create mappings. */ public DefaultNamespacePrefixMapper() < namespaceMap.put("http://www.w3.org/2001/XMLSchema-instance", "xsi"); namespaceMap.put("https://www.intertech.com/software-consulting-services/", "consult"); namespaceMap.put("http://www.w3.org/2003/05/soap-envelope/", "soap"); >/* (non-Javadoc) * Returning null when not found based on spec. * @see com.sun.xml.bind.marshaller.NamespacePrefixMapper#getPreferredPrefix(java.lang.String, java.lang.String, boolean) */ @Override public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) < return namespaceMap.getOrDefault(namespaceUri, suggestion); >>
Configure
Set the “com.sun.xml.bind.namespacePrefixMapper” property on the marshaller to an instance of your mapper. Once set, any time you marshal your JAXB object to XML, it will use your mapper to get the prefix for a given namespace.
Spring’s Jaxb2Marshaller
To configure Spring’s Jaxb2Marshaller to use your NamespacePrefixMapper, you should set the marshallerProperties map on the Jaxb2Marshaller bean.
Java’s Marshaller
To configure the javax.xml.bind.Marshaller , you can set the property directly on the marshaller by calling marshaller.setProperty(“com.sun.xml.bind.namespacePrefixMapper”, new DefaultNamespacePrefixMapper());
Example: (line 25)
import javax.xml.bind.*; import javax.xml.stream.*; import java.io.*; public class SomeService < // JAXBContext is thread safe and can be created once private JAXBContext jaxbContext; public SomeService() < try < // create context with ":" separated list of packages that // contain your JAXB ObjectFactory classes jaxbContext = JAXBContext.newInstance( "com.intertech.consulting" + ":org.w3._2003._05.soap_envelope"); >catch (Exception e) < throw new IllegalStateException(e); >> public String marshal(JAXBElement jaxbElement) < try < Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new DefaultNamespacePrefixMapper()); StringWriter stringWriter = new StringWriter(); marshaller.marshal(jaxbElement, stringWriter); return stringWriter.toString(); >catch (Exception e) < throw new IllegalStateException(e); >> >
Note: If you use the same mappings across your application, you can create one instance of the mapper and share it.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Jaxb2 ‘namespace-prefix’ plugin that allows to define customized XML namespaces prefixes within the bindings.xml file.
License
Siggen/jaxb2-namespace-prefix
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Jaxb2 ‘namespace-prefix’ plugin that adds jakarta.xml.bind.annotation.XmlNs annotations to package-info.java file according to specific definition in the bindings.xml file. Those annotations associate namespace prefixes with XML namespace URIs.
The following package-info.java is generated automatically with the XmlNs annotation :
@jakarta.xml.bind.annotation.XmlSchema(namespace = "http://www.ech.ch/xmlns/eCH-0007/3", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = < @jakarta.xml.bind.annotation.XmlNs(namespaceURI = "http://www.ech.ch/xmlns/eCH-0007/3", prefix = "eCH-0007") >) package ch.ech.ech0007.v3;
And then, Jaxb2 will build Xml structure that look like this :
xml version="1.0" encoding="UTF-8"?> eCH-0007:municipalityRoot xmlns:eCH-0007="http://www.ech.ch/xmlns/eCH-0007/3"> eCH-0007:swissMunicipalityType> . eCH-0007:swissMunicipalityType> eCH-0007:municipalityRoot>
Instead of the default prefix numbering scheme :
xml version="1.0" encoding="UTF-8"?> ns1:municipalityRoot xmlns:ns1="http://www.ech.ch/xmlns/eCH-0007/3"> ns1:swissMunicipalityType> . ns1:swissMunicipalityType> ns1:municipalityRoot>
Example’s configuration with the maven-jaxb2-plugin :
plugin> groupId>org.jvnet.jaxb2.maven2groupId> artifactId>maven-jaxb2-pluginartifactId> version>0.8.0version> configuration> schemaDirectory>src/main/resourcesschemaDirectory> catalog>src/main/resources/catalog.xmlcatalog> schemaIncludes> include>*.xsdinclude> schemaIncludes> bindingDirectory>src/main/resourcesbindingDirectory> bindingIncludes> include>bindings.xmlinclude> bindingIncludes> args> arg>-extensionarg> arg>-Xnamespace-prefixarg> args> configuration> executions> execution> goals> goal>generategoal> goals> execution> executions> dependencies> dependency> groupId>org.jvnet.jaxb2_commonsgroupId> artifactId>jaxb2-namespace-prefixartifactId> version>1.3version> dependency> dependencies> plugin>
Example of bindings.xml file :
xml version="1.0"?> jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:namespace="http://jaxb2-commons.dev.java.net/namespace-prefix" xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd http://jaxb2-commons.dev.java.net/namespace-prefix https://raw.githubusercontent.com/Siggen/jaxb2-namespace-prefix/master/src/main/resources/prefix-namespace-schema.xsd"> jxb:bindings schemaLocation="eCH-0007-3-0.xsd"> jxb:schemaBindings> jxb:package name="ch.ech.ech0007.v3" /> jxb:schemaBindings> jxb:bindings> namespace:prefix name="eCH-0007" /> Additional @XmlNs prefix declarations to take effect for this schema/package --> namespace:prefix name="xsi" namespaceURI="http://www.w3.org/2001/XMLSchema-instance" /> jxb:bindings> jxb:bindings> jxb:bindings>
- Version 2.0 (pending) : Java 11 + migrated to Jakarta namespaces (https://blogs.oracle.com/javamagazine/transition-from-java-ee-to-jakarta-ee)
- Version 1.3 (2017.02.07) : Implemented support for XSDs with only element definitions and no type definition (@solind).
- Version 1.2 (2016.11.30) : Implemented support for multiple @XmlNs declarations within a package, controlled by the bindings file (@MikeEdgar).
- Version 1.1 (2012.06.12) : Implemented support for multiple schemas (with different namespaces) that bind to the same java package.
- Version 1.0 (2012.06.01) : First version.
About
Jaxb2 ‘namespace-prefix’ plugin that allows to define customized XML namespaces prefixes within the bindings.xml file.
Java XML and JSON Binding
Object-to-XML and object-to-JSON mapping using JAXB and EclipseLink MOXy.
Pages
November 30, 2011
JAXB and Namespace Prefixes
In a previous post I covered how to use namespace qualification with JAXB. In this post I will cover how to control the prefixes that are used. This is not covered in the JAXB (JSR-222) specification but I will demonstrate the extensions available in both the reference and EclipseLink MOXy implementations for handling this use case.
The following domain model will be used for this post. The @XmlRootElement and @XmlElement annotation are used to specify the appropriate namespace qualification.
package blog.prefix; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace="http://www.example.com/FOO") public class Root < private String a; private String b; private String c; @XmlElement(namespace="http://www.example.com/BAR") public String getA() < return a; >public void setA(String a) < this.a = a; >@XmlElement(namespace="http://www.example.com/FOO") public String getB() < return b; >public void setB(String b) < this.b = b; >@XmlElement(namespace="http://www.example.com/OTHER") public String getC() < return c; >public void setC(String c) < this.c = c; >>
We will use the following code to populate the domain model and produce the XML.
package blog.prefix; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo < public static void main(String[] args) throws Exception < JAXBContext ctx = JAXBContext.newInstance(Root.class); Root root = new Root(); root.setA("A"); root.setB("B"); root.setC("OTHER"); Marshaller m = ctx.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(root, System.out); >>
XML like the following is produced by default. The JAXB implementation has arbitrarily assigned prefixes to the namespace URIs specified in the domain model:
The reference and Metro implementations of JAXB provide a mechanism called NamespacePrefixMapper to control the prefixes that will be assigned to namespaces.
package blog.prefix; import com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper; //import com.sun.xml.bind.marshaller.NamespacePrefixMapper; public class MyNamespaceMapper extends NamespacePrefixMapper < private static final String FOO_PREFIX = ""; // DEFAULT NAMESPACE private static final String FOO_URI = "http://www.example.com/FOO"; private static final String BAR_PREFIX = "bar"; private static final String BAR_URI = "http://www.example.com/BAR"; @Override public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) < if(FOO_URI.equals(namespaceUri)) < return FOO_PREFIX; >else if(BAR_URI.equals(namespaceUri)) < return BAR_PREFIX; >return suggestion; > @Override public String[] getPreDeclaredNamespaceUris() < return new String[] < FOO_URI, BAR_URI >; > >
The NamespacePrefixMapper is set on an instance of Marshaller. I would recommend wrapping the setPropery call in a try/catch block so that your application does not fail if you change JAXB implementations .
package blog.prefix; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo < public static void main(String[] args) throws Exception < JAXBContext ctx = JAXBContext.newInstance(Root.class); Root root = new Root(); root.setA("A"); root.setB("B"); root.setC("OTHER"); Marshaller m = ctx.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); try < m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new MyNamespaceMapper()); //m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new MyNamespaceMapper()); >catch(PropertyException e) < // In case another JAXB implementation is used >m.marshal(root, System.out); > >
The resulting document now uses the NamespacePrefixMapper to determine the prefixes that should be used in the resulting document.
MOXy will use the namespace prefixes as they are defined on the @XmlSchema annotation. In order for MOXy to be able to use the default namespace the elementFormDefault property on the @XmlSchema annotation must be set to XmlNsForm.QUALIFIED.
@XmlSchema( elementFormDefault=XmlNsForm.QUALIFIED, namespace="http://www.example.com/FOO", xmlns= <@XmlNs(prefix="bar", namespaceURI="http://www.example.com/BAR")>) package blog.prefix; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
The resulting document now uses the xmlns setting from the @XmlSchema annotation to determine the prefixes that should be used in the resulting document.