创建和编组这样的根元素:
JAXBElement<Payment> jbe;
if(payment.getResponse() != null){
jbe = wrap(null, "PaymentResponse", payment);
} else {
jbe = wrap(null, "PaymentRequest", payment);
}
m.marshal(jbe, sw);
用简单的辅助方法
<T> JAXBElement<T> wrap(String ns, String tag, T o){
QName qtag = new QName(ns, tag);
Class<?> clazz = o.getClass();
@SuppressWarnings("unchecked")
JAXBElement<T> jbe = new JAXBElement(qtag, clazz, o);
return jbe;
}
一种简单的方法,使解组可能是创建两个子类PaymentResponse和PaymentRequest充当@XmlRootElements。该的ObjectFactory包含
@XmlElementDecl(namespace = "", name = "PaymentRequest")
public JAXBElement<PaymentRequest>
createPaymentRequest(PaymentRequest value) {
return new JAXBElement<PaymentRequest>(_Payment_QNAME, PaymentRequest.class, null, value);
}
@XmlElementDecl(namespace = "", name = "PaymentResponse")
public JAXBElement<PaymentResponse>
createPaymentResponse(PaymentResponse value) {
return new JAXBElement<PaymentResponse>(_Payment_QNAME, PaymentResponse.class, null, value);
}
解组:
JAXBContext jc = JAXBContext.newInstance(PACKAGE);
Unmarshaller m = jc.createUnmarshaller();
JAXBElement<?> tb = null;
try {
Payment payment = readFrom(Payment.class);
} catch(Exception e ){
}
和方法readFrom:
public <T> T readFrom(Class<T> type) throws Exception {
try {
JAXBContext jc = JAXBContext.newInstance(PACKAGE);
Unmarshaller u = jc.createUnmarshaller();
JAXBElement<T> jbe = (JAXBElement<T>)u.unmarshal(new File(XMLIN));
return type.cast(jbe.getValue());
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
谢谢!不过,我在这里看到两个问题。在编组期间,您必须明确指定根元素的名称。为了实现反编组,你需要改变类的结构(通过为请求和响应创建不同的类) - 不幸的是,我不能这样做。所以,我找到了另一个解决方案,请看下一个答案。 –
请求和响应的“不同类”不会影响应用程序的其余部分,它们在别处不可见。 – laune