package me.test;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.XMLContext;
// Question: how to marshal/unmarshall List
public class TestCastor {
public static void main(String[] args) throws Exception {
testIntrospectionMode();
}
public static void testIntrospectionMode() throws Exception {
System.out.println("\n----------------------testIntrospectionMode()");
Person son = new Person();
Person mom = new Person();
// -----------------------Person:Son----------------------
son.setName("son");
son.setAge(25);
son.setMale(true);
Calendar calendar = Calendar.getInstance();
calendar.set(1985, 4, 5, 5, 5, 5);
calendar.set(Calendar.MILLISECOND, 5);
son.setBirthday(calendar.getTime());
son.setAlias(new String[] { "S_A_0", "S_A_1", "S_A_2" });
son.setImageData(new byte[] { 1, 2, 3, 4 });
son.setFavors(Arrays.asList(new String[] { "S_F_0", "S_F_1", "S_F_2",
" test \n\t<>,\"\"_'ABC'&&|| " }));
Map<String, String> addrs = new HashMap<String, String>(); // unOrdered
addrs.put("HN", "HeNan");
addrs.put("SD", "ShanDong");
son.setAddrs(addrs);
son.setParent(mom);
// -----------------------Person:Mom----------------------
mom.setName("mom");
mom.setAge(50);
mom.setMale(false);
calendar.set(1960, 5, 6, 6, 6, 6);
calendar.set(Calendar.MILLISECOND, 6);
mom.setBirthday(calendar.getTime());
mom.setAlias(new String[] { "M_A_0", "M_A_1", "M_A_2" });
mom.setImageData(new byte[] { 10, 20, 30, 40 });
mom
.setFavors(Arrays.asList(new String[] { "M_F_0", "M_F_1",
"M_F_2" }));
addrs = new HashMap<String, String>();
addrs.put("BJ", "BeiJing");
addrs.put("TJ", "TianJin");
mom.setAddrs(addrs);
mom.setChild(son); // NOTICE : Cycle Reference
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = new LinkedHashMap<String, String>(); // ordered
map.put("AAA", "111");
map.put("BBB", "222");
list.add(map);
// Prepare context
StringWriter writer = new StringWriter();
Mapping mapping = new Mapping();
mapping.loadMapping(Person.class.getResource("Person-mapping.xml"));
XMLContext context = new XMLContext();
context.addMapping(mapping);
// Marshal (Bean -> XML)
System.out.println("\n-------Marshall (Bean -> XML)");
Marshaller marshaller = context.createMarshaller();
marshaller.setWriter(writer);
marshaller.marshal(son);
System.out.println(writer);
// UnMarshal (XML -> Bean)
System.out.println("\n-------UnMarshall (XML -> Bean)");
Unmarshaller unmarshaller = context.createUnmarshaller();
Person newSon = (Person)unmarshaller.unmarshal(new StringReader(writer.toString()));
System.out.println(newSon.toString());
}
}
|