我可以使用如下所示的“Wrapper”类来编组一个 ObservableList。但我无法将它解组回之前的包装类。
这个想法是:我有一个“费用”的 ObservableList。我把这个 List 放到一个包装类中,并将这个类保存到 XML。结果如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<List>
<root>
<category>[none]</category>
<period>Year</period>
<title>asd</title>
<value>354</value>
</root>
</List>
我无法将它带回包装对象。我真的很感激任何帮助。
主类 JAXBContext(对所有人可见):
JAXBContext jc = JAXBContext.newInstance(MyWrapperForList.class, Expense.class);
主类 SAVEBUTTON:
public class SaveButtonListener implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent arg0) {
File serializedFile = new File(PATH);
try {
if (serializedFile.exists() == false)
serializedFile.createNewFile();
PrintWriter xmlOut = new PrintWriter(serializedFile);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
List<Expense> saveList = new ArrayList<>();
saveList.addAll(data);
MyWrapperForList<Expense> wrapper = new MyWrapperForList<>(saveList);
JAXBElement<MyWrapperForList> jaxbElement = new JAXBElement<>(
new QName("List"), MyWrapperForList.class, wrapper);
m.marshal(jaxbElement, xmlOut);
xmlOut.flush();
xmlOut.close();
主类-LOADBUTTON:
public class LoadButtonListener implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent arg0) {
try {
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource(PATH);
MyWrapperForList<Expense> unwrapper = unmarshaller.unmarshal(xml,
MyWrapperForList.class).getValue();
List<Expense> tempList = new ArrayList<>();
tempList.addAll(unwrapper.getItems());
System.out.println(tempList.get(0).getTitle());
} catch (Exception e) {
e.printStackTrace();
}
}
}
包装类:
公共类 MyWrapperForList {
private List<Expense> list;
public MyWrapperForList() {
list = new ArrayList<>();
}
public MyWrapperForList(List<Expense> expenses) {
this.list = expenses;
}
@XmlAnyElement(lax=true)
public List<Expense> getItems() {
return list;
}
}
费用等级:
@XmlRootElement(name = "root") 公共类费用 {
private String title;
private String category;
private String period;
private String value;
public Expense() {} //Default constructor is needed for XML-handling
public Expense(String title, String value, String period, String category) {
this.title = title;
this.value = value;
this.period = period;
this.category = category;
}
@XmlElement(name = "title")
public String getTitle() {
return this.title;
}
@XmlElement(name = "category")
public String getCategory() {
return this.category;
}
@XmlElement(name = "period")
public String getPeriod() {
return this.period;
}
@XmlElement(name = "value")
public String getValue() {
return this.value;
}
}
我使用了 Blaise Doughan 的本教程:http: //blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html