import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class TestJAXB {
public static void main(String[] args) {
try {
//read xml file to Java object
Trans trans = TestJAXB.readString(Trans.class,"input.xml");
List<Tran> datas = trans.getDatas();
for (Tran o : datas) {
System.out.println(o.getReturnCode()+";"+o.getReturnInfo());
}
//write java object to xml
Tran tran = new Tran();
tran.setOrderNo(11111L);
tran.setRequestId(22222L);
tran.setReturnCode("0000");
tran.setReturnInfo("success");
Tran tran2 = new Tran();
tran2.setOrderNo(33333L);
tran2.setRequestId(44444L);
tran2.setReturnCode("0001");
tran2.setReturnInfo("failure");
Trans trxs = new Trans();
List<Tran> list = new ArrayList<Tran>();
list.add(tran);
list.add(tran2);
trxs.setDatas(list);
File file = new File("D:/output.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Trans.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(trxs, file);
jaxbMarshaller.marshal(trxs, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static <T> T readString(Class<T> clazz, String context) throws JAXBException {
try {
JAXBContext jc = JAXBContext.newInstance(clazz);
Unmarshaller u = jc.createUnmarshaller();
return (T) u.unmarshal(new File(context));
} catch (JAXBException e) {
throw e;
}
}
}