Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Namespace of a JAXB object

Currently I am marshalling a JAXB object to an output stream with the following code

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
ByteArrayOutputStream out = new ByteArrayOutputStream();
marshaller.marshal(new JAXBElement(new QName("hard_coded_namespace", clazz.getSimpleName()), clazz, obj), out);

I would like to replace "hard_coded_namespace" with the namespace contained within the JAXB "obj" (or one of its attributes, they currently should share the same NS).

Any ideas how to get at the NS information BEFORE marshaling? In the output stream, the Namespaces appear. So they are somewhere in the "obj".

[UPDATE] As pointed out in the answers below, I don't need to set the the JAXB_FRAGMENT property. I changed it to:

    JAXB.marshal(new JAXBElement<T>(new QName("hard_coded_namespace", rootName), clazz, jaxbObject), out);
like image 525
Chris Avatar asked Jun 08 '12 14:06

Chris


1 Answers

For now, this is the solution I found:

    String nsURI = "";
    for(Annotation annotation: jaxbObject.getClass().getPackage().getAnnotations()){
        if(annotation.annotationType() == XmlSchema.class){
            nsURI = ((XmlSchema)annotation).namespace();
            break;
        }
    }

More elegant solutions are welcome :-)

like image 133
Chris Avatar answered Sep 28 '22 09:09

Chris