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);
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With