Se podría aprovechar JAXBIntrospector para hacer lo siguiente:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBIntrospector;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
Object value = "Hello World";
//Object value = new Bar();
JAXBContext jc = JAXBContext.newInstance(String.class, Bar.class);
JAXBIntrospector introspector = jc.createJAXBIntrospector();
Marshaller marshaller = jc.createMarshaller();
if(null == introspector.getElementName(value)) {
JAXBElement jaxbElement = new JAXBElement(new QName("ROOT"), Object.class, value);
marshaller.marshal(jaxbElement, System.out);
} else {
marshaller.marshal(value, System.out);
}
}
@XmlRootElement
public static class Bar {
}
}
Con el código anterior cuando el JAXBElement se marshalled que será calificado con un atributo xsi: tipo correspondiente al tipo de esquema apropiado:
<ROOT
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Hello World</ROOT>
para eliminar la calificación puede simplemente cambiar la línea que crea el JAXBElement a:
JAXBElement jaxbElement = new JAXBElement(new QName("ROOT"), value.getClass(), value);
Esto dará como resultado el siguiente código XML:
<ROOT>Hello World</ROOT>
¡Funciona a la perfección! ¿Quizás sabes cómo deshacerte del atributo 'xsi: type'? Esto es lo que obtengo para un objeto 'String':' (239) 555 2390 ' –
yegor256
@Vincenzo He actualizado mi respuesta con detalles sobre cómo eliminar el atributo xsi: type. –
@BlaiseDoughan, consulte este problema: http://stackoverflow.com/questions/26816798/objectfactory-methods-generated-by-jaxb – Spartan