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="")
 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 =     
 String uri = ""+version;


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

2 answers

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 ("".equals(uri) {
    uri = "" + version;
  delegate.writeNamespace(prefix, uri);




Do you consider using XSL-T transformation? Depending on your schema, it might be relatively easy to replace the namespace after sorting.



All Articles