import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; public class JAXBExample { public static class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public static void main(String[] args) { try { JAXBContext jaxbContext = JAXBContext.newInstance(Person.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Person person = new Person(); person.setAge(25); marshaller.marshal(person, new File("person.xml")); Person unmarshalledPerson = (Person) unmarshaller.unmarshal(new File("person.xml")); System.out.println("Name: " + unmarshalledPerson.getName()); System.out.println("Age: " + unmarshalledPerson.getAge()); } catch (JAXBException e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文