2

I'm trying to output the schemaLocation attribute properly when marshalling an xjc-generated class instance. The root element class looks like:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "rootElement"
})
@XmlRootElement(name = "ROOTELEMENT")
public class ROOTELEMENT {
    // Members
}

I see there's a package-info.java class sitting in the package where all generated classes are, with the following contents:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "http://my.own.namespace", 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package my.generated.classes.package;

The answer to JAXB XJC code generation - “schemaLocation” missing in xml generated by Marshaller proposes setting the Marshaller.JAXB_SCHEMA_LOCATION property, and it indeed works:

marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://my.own.namespace my_schema.xsd");

But I'd like to avoid typing the namespace, as in:

String namespace = getNamespace(rootElementInstance);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, namespace + " my_schema.xsd");

I'd appreciate any tips on how to implement the getNamespace() function.


EDIT: I've seen that the XmlRootElement and XmlType annotations have the namespace() method, that seems to be what I'm after (actually, they seem to delegate on the XmlSchema provided in package-info.java). However, I cannot get an instance of ROOTELEMENT casted to any of these types.

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161

1 Answers1

3

You need to grab a hand on your package (for example using ROOTELEMENT.class.getPackage() if ROOTELEMENT is in the package you want). Then you can simply process it as follow:

Package package = // Here retrieve the package;
String namespace = package.getAnnotation(XmlSchema.class).namespace();
...etc...
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • That worked. Glad to have learnt something new. Thank you. However, I'd expect JAXB to provide a less 'manual' way to achieve this. I'll leave the answer unaccepted for now, in case there's another more elegant option. – Xavi López Apr 30 '12 at 13:49
  • 1
    +1 - @XaviLópez - JAXB (JSR-222) currently doesn't offer API to introspect the metadata (maybe it should offer something like JPA does). The approach give here is probably your best bet. – bdoughan Apr 30 '12 at 20:16