Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing/Deserialize XML to JavaObjects

Tags:

java

xml

jaxb

xsd

i started a small new project and i want to deserialize objects from XML.

i created a xsd:

http://pastebin.com/n1pwjRGX

and an example XML File :

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<hdb>
    <country code="DE">
        <variableHoliday daysAfterEaster="49" name="PENTECOAST" />
        <fixedHoliday month="JANUARY" day="1" name="NEWYEAR" />
        <region code="sa">
            <fixedHoliday month="APRIL" day="1" name="FUNNYDAY" />
            <variableHoliday daysAfterEaster="0" name="EASTERSUNDAY" />
        </region>
        <region code="ba">
            <variableHoliday daysAfterEaster="12" name="CORPUSCHRISTI" />
        </region>
    </country>
    <country code="US">
        <fixedHoliday month="JULY" day="4" name="INDEPENDENCEDAY" />
    </country>
    <country code="AL">
        <fixedHoliday month="JULY" day="4" name="INDEPENDENCEDAY" />
    </country>
</hdb>

Which should use the xsd and so on.

So how can i achive the deserialization of these XML to a nice Java-Object Structure?

Mabe like :

class HDB {
    private HashMap<CountryCode,Country> map;
}

class Country {
    private List<Holiday> list; // or two Lists with <variableHoliday> and <fixedHoliday>
    private List<Region> regions;
}

class Region{
    private List<Holiday> list; // or two Lists with <variableHoliday> and <fixedHoliday>
}

class variableHoliday {
    private String name;
    private int daysAfterEaster;
}
class fixedHoliday {
    private String name;
    private int day;
    private MonthName month; // while MonthName is an enum defined like the enum from XSD
}

Any ideas how to achive that easy?

I thought of jaxb an tried some stuff, but it seems to me (im a beginner with jaxb) that its hard to achive this XML structure because of maps cant be written like v.

like image 830
Smoki Avatar asked Jan 10 '23 07:01

Smoki


1 Answers

use

xjc your_xsd_name -p packagename 

to generate Pojos, xjc is xml java compiler that comes with jdk.

once your classes are generated use jaxb as follows

JAXB Marshalling

    HDB hdb = new HDB(); 
    JAXBContext jaxbContext = JAXBContext.newInstance(HDB.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.marshal(hdb, file);
    jaxbMarshaller.marshal(hdb, System.out);

JAXB Unmarshalling

    File file = new File("your xml file");
    JAXBContext jaxbContext = JAXBContext.newInstance(hdb.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    HDB hdb = (HDB) jaxbUnmarshaller.unmarshal(file);
    System.out.println(hdb);

Visit following link for more info JAXB marshalling and unmarshalling

like image 198
Santosh Joshi Avatar answered Jan 18 '23 10:01

Santosh Joshi