1// An Example of using JAXB to convert a map to XML , written in Java.
2public static void main(String[] args) throws JAXBException
3{
4 HashMap<Integer, Employee> map = new HashMap<Integer, Employee>();
5
6 Employee emp1 = new Employee();
7 emp1.setId(1);
8 emp1.setFirstName("Lokesh");
9 emp1.setLastName("Gupta");
10 emp1.setIncome(100.0);
11
12 Employee emp2 = new Employee();
13 emp2.setId(2);
14 emp2.setFirstName("John");
15 emp2.setLastName("Mclane");
16 emp2.setIncome(200.0);
17
18 map.put( 1 , emp1);
19 map.put( 2 , emp2);
20
21 //Add employees in map
22 EmployeeMap employeeMap = new EmployeeMap();
23 employeeMap.setEmployeeMap(map);
24
25 /******************** Marshalling example *****************************/
26
27 JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class);
28 Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
29
30 jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
31
32 jaxbMarshaller.marshal(employeeMap, System.out);
33 jaxbMarshaller.marshal(employeeMap, new File("c:/temp/employees.xml"));
34}
35
36Output:
37
38<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
39<employees>
40 <employeeMap>
41 <entry>
42 <key>1</key>
43 <value>
44 <id>1</id>
45 <firstName>Lokesh</firstName>
46 <lastName>Gupta</lastName>
47 <income>100.0</income>
48 </value>
49 </entry>
50 <entry>
51 <key>2</key>
52 <value>
53 <id>2</id>
54 <firstName>John</firstName>
55 <lastName>Mclane</lastName>
56 <income>200.0</income>
57 </value>
58 </entry>
59 </employeeMap>
60</employees>
61
1// An example of using JAXB to convert XML to MAP
2
3private static void unMarshalingExample() throws JAXBException
4{
5 JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeMap.class);
6 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
7 EmployeeMap empMap = (EmployeeMap) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") );
8
9 for(Integer empId : empMap.getEmployeeMap().keySet())
10 {
11 System.out.println(empMap.getEmployeeMap().get(empId).getFirstName());
12 System.out.println(empMap.getEmployeeMap().get(empId).getLastName());
13 }
14}
15
16Output:
17
18Lokesh
19Gupta
20John
21Mclane
22