In my test utility code, I print XML content like this.
public static <T> void printXml(final Class<T> type, final T instance)
throws JAXBException {
final JAXBContext context = JAXBContext.newInstance(type);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (type.getAnnotation(XmlRootElement.class) == null) {
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
final XmlType xmlType = type.getAnnotation(XmlType.class);
// xmlType.name() -> "##default"
marshaller.marshal(
new JAXBElement<>(new QName(xmlType.namespace(),
xmlType.name()), type, instance),
System.out);
return;
}
marshaller.marshal(instance, System.out);
}
Types with @XmlRootElement
work just fine.
But when I tried to print a type which has not an @XmlRootElement
I got this.
<##default xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
...
</##default>
The xmlns
part is fine. The marshaller found the namespaceUri I want.
The question is, see that ##default
?, how can I find the name part?
I want this.
<someName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="...">
...
</someName>
If a name isn't specified on the annotation it defaults to ##default
. To handle this case you would need to do what JAXB impls do and apply the algorithm defined in the JSR-222 specification on the short class name to get the name.