Skip to content

Instantly share code, notes, and snippets.

@rschumm
Created May 4, 2012 09:32
Show Gist options
  • Save rschumm/2593606 to your computer and use it in GitHub Desktop.
Save rschumm/2593606 to your computer and use it in GitHub Desktop.
Simple JAXB marshalling und unmarshalling
package ch.schumm.fakeservice.model;
import java.io.Serializable;
public class Adresse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String strasse;
String ort;
public String getStrasse() {
return strasse;
}
public void setStrasse(String strasse) {
this.strasse = strasse;
}
public String getOrt() {
return ort;
}
public void setOrt(String ort) {
this.ort = ort;
}
@Override
public String toString() {
return "an " + strasse + " in " + ort;
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<kunde>
<adresse>
<ort>Coburg</ort>
<strasse>Schlossgasse</strasse>
</adresse>
<name>Schumm</name>
<vorname>Josef</vorname>
</kunde>
package ch.schumm.fakeservice.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Kunde implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4539708693456998133L;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public Adresse getAdresse() {
return adresse;
}
public void setAdresse(Adresse adresse) {
this.adresse = adresse;
}
String name;
String vorname;
Adresse adresse;
@Override
public String toString() {
return vorname + " " + name + " wohnt " + adresse.toString();
}
}
package ch.schumm.fakeservice.main;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import ch.schumm.fakeservice.model.Adresse;
import ch.schumm.fakeservice.model.Kunde;
/**
* Marshallt einen Kunden in ein XML-File, unmarshallt ihn grad wieder und zeigt ihn an.
*
*/
public class Main {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Kunde.class);
//Marshalling...
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Kunde kunde = generateModel();
m.marshal(kunde, new File("josef.xml"));
//Unamarshalling...
Unmarshaller u = context.createUnmarshaller();
Object object = u.unmarshal(new File("josef.xml"));
System.out.println(object.toString());
}
private static Kunde generateModel() {
Kunde kunde = new Kunde();
kunde.setName("Schumm");
kunde.setVorname("Josef");
Adresse adresse = new Adresse();
adresse.setOrt("Coburg");
adresse.setStrasse("Schlossgasse");
kunde.setAdresse(adresse);
return kunde;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment