Reputation: 5246
I marshall some object but the problem is JAXB writes default namespace prefixes instead of predefined ones. Is there any idea what can cause this problem?
What I expect to see;
<xbrli:entity>
....
What I got;
<ns3:entity>
....
I generated all classes(including package-infos)
example package-info;
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.xbrl.org/2003/instance",
xmlns = {
@XmlNs(namespaceURI = "http://www.xbrl.org/2003/instance", prefix = "xbrli2")
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.xbrl._2003.instance;
import javax.xml.bind.annotation.XmlNs;
Upvotes: 1
Views: 629
Reputation: 149047
JAXB (JSR-222) does not offer a standard way to specify the namespace prefix used.
NamespacePrefixMapper
For the JAXB reference implementations and recent versions of EclipseLink JAXB (MOXy) you can use the NamespacePrefixMapper
extension to control the namespace prefixes used.
MyNamespaceMapper
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 };
}
}
Specifying the NamespacePrefixMapper
Below is an example of how the NamespacePrefixMapper
is set on the Marshaller
.
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
}
@XmlSchema
EclipseLink JAXB (MOXy) and recent versions of the JAXB reference implementation will use the namespace prefixes defined on the package level @XmlSchema
annotation.
@XmlSchema(
elementFormDefault=XmlNsForm.QUALIFIED,
namespace="http://www.example.com/FOO",
xmlns={
@XmlNs(prefix="", namespaceURI="http://www.example.com/FOO")
@XmlNs(prefix="bar", namespaceURI="http://www.example.com/BAR")
}
)
package blog.prefix;
import javax.xml.bind.annotation.*;
Upvotes: 1