Marhall e Unmarshall di un file xml con JAXB

import it.gsoftware.xml.model.Job;

public class Main {

	String PATH = "file.xml"; 
	
	
	public Main(){
		
		 marshal();
		 unmarshal();
	}
	
	private void marshal(){
		
		Job job = new Job();
		job.setTitle("Java Developer");
		job.setLocation("Rome");
		job.setDescription("Are you a Java Developer?");
			
		File file = new File("file.xml");
		
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Job.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			jaxbMarshaller.marshal(job, file);
			jaxbMarshaller.marshal(job, System.out);
			
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	
	private void unmarshal(){
		
		File file = new File("file.xml");
		
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Job.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Job job = (Job) jaxbUnmarshaller.unmarshal(file);
			System.out.println(job);
					
		} catch (JAXBException e) {
			e.printStackTrace();
		}		
		
	}
	
	
	public static void main(String[] args) {

		new Main();		
	}

}

 

package it.gsoftware.xml.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Job {

	private String title;
	private String location;
	private String description;
	
	public String getTitle() {
		return title;
	}
	@XmlElement
	public void setTitle(String title) {
		this.title = title;
	}
	public String getLocation() {
		return location;
	}
	@XmlElement
	public void setLocation(String location) {
		this.location = location;
	}
	public String getDescription() {
		return description;
	}
	@XmlElement
	public void setDescription(String description) {
		this.description = description;
	}
	
	@Override
	public String toString() {
		return "Job [title=" + title + ", location=" + location + ", description=" + description + "]";
	}
	
	
}
Marco Ballante 09/02/2017

Per lasciare un commento devi essere autenticato Accedi

Risposte


Dai il tuo contributo, Rispondi alla discussione!


Non hai trovato la risposta che cercavi? Crea tu una nuova discussione
Javajob.it © 2017 - Javajob.it è un progetto realizzato da Gsoftware srls