Sanath
Sanath

Reputation: 4886

setting namespace of objects dynamically in jaxb marshalling

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.

Upvotes: 3

Views: 3162

Answers (2)

chris
chris

Reputation: 3563

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);
}

Upvotes: 2

Patrice M.
Patrice M.

Reputation: 4319

Did you consider using an XSL-T transformation ? Depending on your schema, it could be relatively straight-forward to replace the namespace after marshalling.

Upvotes: 1

Related Questions