Skip to content

Instantly share code, notes, and snippets.

@ppkarwasz
Created January 17, 2021 19:41
Show Gist options
  • Save ppkarwasz/41300cbcc50d75316903fe426b8be9c3 to your computer and use it in GitHub Desktop.
Save ppkarwasz/41300cbcc50d75316903fe426b8be9c3 to your computer and use it in GitHub Desktop.
JAXB: example of remapping of unqualified elements
/*
* Add this annotation to the package:
* @XmlSchema(xmlns = {
* @XmlNs(prefix = "", namespaceURI = Example.NS1),
* @XmlNs(prefix = "name2", namespaceURI = Example.NS2)}, elementFormDefault =
* XmlNsForm.QUALIFIED)
*/
public class Example {
@XmlType(namespace = XMLConstants.NULL_NS_URI)
public static class Attribute {
private String key;
private String value;
public Attribute(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@XmlRootElement(namespace = NS1)
public static class Namespace1 {
private List<Attribute> attributes = new ArrayList<>();
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public Namespace1 addAttribute(Attribute attribute) {
attributes.add(attribute);
return this;
}
}
@XmlRootElement(namespace = NS2)
public static class Namespace2 {
private List<Attribute> attributes = new ArrayList<>();
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public Namespace2 addAttribute(Attribute attribute) {
attributes.add(attribute);
return this;
}
}
public static final String NS1 = "namespace1";
public static final String NS2 = "namespace2";
public static void main(String[] arguments) throws JAXBException {
final Namespace1 ns1 = new Namespace1().addAttribute(new Attribute("key1", "value1"));
final Namespace2 ns2 = new Namespace2().addAttribute(new Attribute("key2", "value2"));
serialize(ns1, true);
serialize(ns2, true);
serialize(ns1, false);
serialize(ns2, false);
}
private static void serialize(Object obj, boolean remap) throws JAXBException {
final XmlRootElement rootElement = obj.getClass().getAnnotation(XmlRootElement.class);
Map<String, String> properties = null;
if (remap && rootElement != null) {
properties = Collections.singletonMap(JAXBRIContext.DEFAULT_NAMESPACE_REMAP, rootElement.namespace());
}
final JAXBContext ctx = JAXBContext.newInstance(new Class[]{obj.getClass()}, properties);
final Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(obj, System.out);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment