<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="person" type="personType"/> <xs:complexType name="personType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="age" type="xs:int"/> </xs:sequence> </xs:complexType> </xs:schema> xjc person.xsd 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 jaxbContext = JAXBContext.newInstance(Person.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Person person = new Person(); person.setName("John"); person.setAge(30); marshaller.marshal(person, new File("person.xml")); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Person personFromFile = (Person) unmarshaller.unmarshal(new File("person.xml")); System.out.println("Name: " + personFromFile.getName()); System.out.println("Age: " + personFromFile.getAge()); } catch (Exception e) { e.printStackTrace(); } } }


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