<?xml version="1.0" encoding="UTF-8"?> <customer> <id>123</id> <name>John Doe</name> <email>john.doe@example.com</email> </customer> import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElement; @XmlRootElement public class Customer { private int id; private String name; private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name="email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 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) { try { JAXBContext context = JAXBContext.newInstance(Customer.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Unmarshaller unmarshaller = context.createUnmarshaller(); Customer customer = new Customer(); customer.setId(123); customer.setName("John Doe"); customer.setEmail("john.doe@example.com"); marshaller.marshal(customer, new File("customer.xml")); File xmlFile = new File("customer.xml"); Customer newCustomer = (Customer) unmarshaller.unmarshal(xmlFile); System.out.println("Customer ID: " + newCustomer.getId()); System.out.println("Customer Name: " + newCustomer.getName()); System.out.println("Customer Email: " + newCustomer.getEmail()); } catch (Exception e) { e.printStackTrace(); } } }


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