I have a situation where I need to setup my namespaces dynamically for my jaxb classes. my namespace in jaxb classes have 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 perfect when I use this static namespacing mechanism, but in my real situation, I need this version to be changed dynamically..
I tried this approach to solve this issue when marshalling
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 throw me an error Invalid state: start tag is not opened at writeNamespace
any input on how this can be resolved is highly appreciated.
You may implement a XMLStreamWriter
that delegates all calls to the original writer, but overrides the writeNamespace(...)
method:
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);
}