<dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>3.0.1</version> </dependency> <employee> <id>1</id> <name>John Doe</name> <salary>50000</salary> </employee> import jakarta.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Employee { private int id; private String name; private int salary; // Getters and setters } import jakarta.xml.bind.*; public class XmlToJavaParser { public static void main(String[] args) throws JAXBException { JAXBContext context = JAXBContext.newInstance(Employee.class); Unmarshaller unmarshaller = context.createUnmarshaller(); FileReader reader = new FileReader("employee.xml"); Employee employee = (Employee) unmarshaller.unmarshal(reader); System.out.println("Employee ID: " + employee.getId()); System.out.println("Employee Name: " + employee.getName()); System.out.println("Employee Salary: " + employee.getSalary()); } } import jakarta.xml.bind.*; public class JavaToXmlGenerator { public static void main(String[] args) throws JAXBException, FileNotFoundException { JAXBContext context = JAXBContext.newInstance(Employee.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Employee employee = new Employee(); employee.setId(1); employee.setName("John Doe"); employee.setSalary(50000); marshaller.marshal(employee, new FileOutputStream("employee.xml")); } }


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