<dependency> <groupId>jakarta.xml.bind</groupId> <artifactId>jakarta.xml.bind-api</artifactId> <version>3.0.1</version> </dependency> import jakarta.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Person { @XmlElement private String name; @XmlElement private int age; // Getters and setters } import jakarta.xml.bind.*; public class XMLToObject { public static void main(String[] args) throws JAXBException { File xmlFile = new File("path/to/xml/file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Person.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Person person = (Person) jaxbUnmarshaller.unmarshal(xmlFile); System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } } import jakarta.xml.bind.*; public class ObjectToXML { public static void main(String[] args) throws JAXBException { Person person = new Person(); person.setName("John Doe"); person.setAge(30); JAXBContext jaxbContext = JAXBContext.newInstance(Person.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(person, System.out); } }


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