import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; public class JAXBExample { public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Unmarshaller unmarshaller = context.createUnmarshaller(); Person person = new Person("John Doe", 25); marshaller.marshal(person, new File("person.xml")); person = (Person) unmarshaller.unmarshal(new File("person.xml")); System.out.println(person); } } import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } @XmlElement public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }


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