創建和編組這樣的根元素:
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