Setting object namespace dynamically in jaxb marshalling
I have a situation where I need to dynamically set my namespaces for my jaxb classes. my namespace in jaxb classes has a version that needs to be dynamically changed.
@XmlRootElement(name = "myobject",namespace="http://myhost.com/version-2")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public class myObject{
}
my marshalling works great when I use this static namespace mechanism, but in my real situation I need this version to change dynamically ..
I tried using this approach to solve this issue when sorting
XMLStreamWriter xmlStreamWriter =
XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter);
String uri = "http://myhost.com/ver-"+version;
//xmlStreamWriter.setDefaultNamespace(uri);
xmlStreamWriter.writeStartDocument("1.0");
xmlStreamWriter.writeNamespace("ns1", uri);
my attempt to use setDefaultNamespace was not successful and writeNamespace gave me an error Invalid state: start tag does not open in the entry namespace
Any input on how this can be resolved is much appreciated.
source to share
You can implement XMLStreamWriter
that delegates all calls to the original author, but overrides the method writeNamespace(...)
:
public void writeNamespace(String prefix, String uri) {
if ("http://myhost.com/version-2".equals(uri) {
uri = "http://myhost.com/version-" + version;
}
delegate.writeNamespace(prefix, uri);
}
source to share