我是JAXB的新手,可能是一个相当简单的解决方案,但我不知道该怎么做 . 我可以从我无法控制的设备接收以下xml .
Sample 1
<LoyaltyID entryMethod="swipe">
<Track1>636497123456678</Track1>
</LoyaltyID>
Sample 2
<LoyaltyID entryMethod="manual">636497123456678</LoyaltyID>
我使用xjc创建了一个具有以下定义的JAXB类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"track1",
"track2",
"track3"
})
@XmlRootElement(name = "LoyaltyID")
public class LoyaltyID {
@XmlElement(name = "Track1")
protected String track1;
@XmlElement(name = "Track2")
protected String track2;
@XmlElement(name = "Track3")
protected String track3;
@XmlAttribute(name = "entryMethod")
protected String entryMethod;
/**
* Gets the value of the track1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTrack1() {
return track1;
}
/**
* Sets the value of the track1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTrack1(String value) {
this.track1 = value;
}
/**
* Gets the value of the track2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTrack2() {
return track2;
}
/**
* Sets the value of the track2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTrack2(String value) {
this.track2 = value;
}
/**
* Gets the value of the track3 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTrack3() {
return track3;
}
/**
* Sets the value of the track3 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTrack3(String value) {
this.track3 = value;
}
/**
* Gets the value of the entryMethod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEntryMethod() {
if (entryMethod == null) {
return "swipe";
} else {
return entryMethod;
}
}
/**
* Sets the value of the entryMethod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEntryMethod(String value) {
this.entryMethod = value;
}
当我解组样本1时,一切都很好,我可以通过调用getTrack1()方法访问LoyaltyID(636497123456678) . 但是,如果我在示例2中收到XML,则无法访问该数据 . 应该指出的是,当entryMethod属性设置为“manual”时,我只收到Sample 2 XML . 我需要不仅可以解组此XML,还可以将其编组回最初发送它的设备 . 有谁知道我怎么能做到这一点?
任何帮助解决这个问题非常感谢 .
谢谢! - 蒂姆
1 回答
您可以使用 JAXB EclipseLink MOXy 实现来访问 XmlPath 注释:
结果如下:
您只需要引用 eclipselink.jar 存档 .