Tuesday, 3 September 2013

Marshall a List to XML works - but how to unmarshall?

Marshall a List to XML works - but how to unmarshall?

I can marshall a ObservableList using a "Wrapper"-class like below. But I
cannot unmarshall it back to the wrapperclass.
The idea is: I have an ObservableList of "Expenses". I put this List into
a wrapper-class and save this class to XML. The result looks like this:
<List>
<expense>
<category>[none]</category>
<period>Year</period>
<title>dfg</title>
<value>4</value>
</expense>
<expense>
<category>[none]</category>
<period>Year</period>
<title>ROBO</title>
<value>1234</value>
</expense>
</List>
I cannot bring it back to the wrapper-object. I really appreciate any kind
of help.
Main-class:
//JAXBContext, used to get a marshaller and an unmarshaller
JAXBContext jc = JAXBContext.newInstance(MyWrapperForList.class,
Expense.class);
//MARSHALLING
PrintWriter xmlOut = new PrintWriter(serializedFile);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
MyWrapperForList<Expense> wrapper = new MyWrapperForList<>(data);
JAXBElement<MyWrapperForList> jaxbElement = new JAXBElement<>(new
QName("List"), MyWrapperForList.class, wrapper);
m.marshal(jaxbElement, xmlOut);
//UNMARSHALLING
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource("C:/users/***/desktop/nub.xml");
MyWrapperForList<Expense> wrapper = (MyWrapperForList<Expense>)
unmarshaller.unmarshal(xml, MyWrapperForList.class).getValue();
data = wrapper.getItems();
Wrapper-class:
public class MyWrapperForList<Expense> {
private ObservableList<Expense> expenses;
public MyWrapperForList() {
expenses = FXCollections.observableArrayList();
}
public MyWrapperForList(ObservableList<Expense> expenses) {
this.expenses = expenses;
}
@XmlAnyElement(lax=true)
public ObservableList<Expense> getItems() {
return expenses;
}
}
Expense-class:
@XmlRootElement
public class Expense {
private String title;
private String category;
private String period;
private String value;
public Expense() {}
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;
}
}
I used this tutorial from Blaise Doughan:
http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html

No comments:

Post a Comment