<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Person { @XmlAttribute private String name; @XmlElement private int age; } import javax.xml.bind.*; public class XmlUtils { public static String toXml(Object obj) throws JAXBException { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); return writer.toString(); } public static <T> T fromXml(String xml, Class<T> clazz) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader reader = new StringReader(xml); return clazz.cast(unmarshaller.unmarshal(reader)); } } public class Main { public static void main(String[] args) throws JAXBException { Person person = new Person(); person.setAge(20); String xml = XmlUtils.toXml(person); System.out.println(xml); Person newPerson = XmlUtils.fromXml(xml, Person.class); System.out.println(newPerson.getName()); System.out.println(newPerson.getAge()); } }


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