感谢您的所有解释和链接,我已经写了这个,以便使用 Annotation Introspection 来处理这两种情况。
这样做的好处是:
- 不修改生成的 java 类
- 允许所有可能的 xsd 格式
它适用于输出和输入,在我看来更通用:
public class JaxbWrapper {
private static boolean isXmlRootElement(Class classT){
Annotation[] annotations = classT.getAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof XmlRootElement){
return true;
}
}
return false;
}
public static Object unmarshall(Class classObjectFactory, Class classObject, XMLStreamReader xmlStreamReader){
Package pack = classObjectFactory.getPackage();
String strPackageName = pack.getName();
Object returnObject = null;
try {
JAXBContext jc = JAXBContext.newInstance(strPackageName, classObjectFactory.getClassLoader());
Unmarshaller unmarshaller = jc.createUnmarshaller();
returnObject = unmarshaller.unmarshal( xmlStreamReader );
boolean bIsRootedElement = isXmlRootElement(classObject);
if(!bIsRootedElement)
{
JAXBElement jaxbElement = (JAXBElement) returnObject;
returnObject = jaxbElement.getValue();
}
}
catch (JAXBException e) {
/*...*/
}
return returnObject;
}
private static void writeToXml(Class classObjectFactory, Object obj, XMLStreamWriter xmlStreamWriter){
Package pack = classObjectFactory.getPackage();
String strPackageName = pack.getName();
try {
JAXBContext jc = JAXBContext.newInstance(strPackageName, classObjectFactory.getClassLoader());
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(obj, xmlStreamWriter);
}
catch(JAXBException e) {
/*...*/
}
}
public static String marshall(Class classObjectFactory, Class classObject, Object obj){
Object objectToMarshall = obj;
boolean bIsRootedElement = isXmlRootElement(classObject);
if(!bIsRootedElement)
{
Package pack = classObjectFactory.getPackage();
String strPackageName = pack.getName();
String strClassName = classObject.getName();
QName qName = new QName(strPackageName, strClassName);
JAXBElement jaxbElement = new JAXBElement(qName, classObject, null, obj);
objectToMarshall = jaxbElement;
}
StringWriter sw = new StringWriter();
XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
XMLStreamWriter xmlStreamWriter = null;
try {
xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(sw);
writeToXml(classObjectFactory, objectToMarshall, xmlStreamWriter);
xmlStreamWriter.flush();
xmlStreamWriter.close();
}
catch (XMLStreamException e) {
/*...*/
}
return sw.toString();
}
}