你應該能夠有類似以下內容的XmlAdapter做到這一點:
一旦你的答案(How do I specify the adapter(s) which JAXB uses for marshaling/unmarshaling data?),你將能夠應用適配器。
以下是它是如何做到的。請注意,以下示例使用EclipseLink JAXB (MOXy),但在使用JAXB參考實現時引發異常。
FamilyMember
package example;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name="FamilyMember")
public class FamilyMember {
private boolean pet;
private String name;
@XmlElementRef
@XmlJavaTypeAdapter(IsPetAdapter.class)
public boolean isPet() {
return pet;
}
public void setPet(boolean pet) {
this.pet = pet;
}
@XmlElement(name="Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
IsPetAdapter
package example;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import forum204.IsPetAdapter.IsPet;
public class IsPetAdapter extends XmlAdapter<IsPet, Boolean> {
@Override
public Boolean unmarshal(IsPet v) throws Exception {
return null != v;
}
@Override
public IsPet marshal(Boolean v) throws Exception {
if(v) {
return new IsPet();
}
return null;
}
@XmlRootElement(name="IsPet")
public static class IsPet {
}
}
演示
package example;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(FamilyMember.class);
Unmarshaller unmarshaller= jc.createUnmarshaller();
FamilyMember fm = (FamilyMember) unmarshaller.unmarshal(new File("input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(fm, System.out);
}
}
這是一種我的問題的觀點。我可以將IsPet解析爲布爾值,但如果它不存在,它將返回null。我不想將它檢查爲null,而是將其值設置爲true,如果不爲null,則返回false。 – troyal 2011-05-11 20:47:15