The main Java classes used are: Javax.xml.bind.jaxbcontext,javax.xml.bind.marshaller (orchestration)
The code mainly shows as follows:
Public classStudent {Private intID; PrivateString name; Private intAge ; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicStudent (intID, String name,intAge ) { Super(); This. ID =ID; This. Name =name; This. Age =Age ; } PublicStudent () {Super(); //TODO auto-generated Constructor stub }}
Importjavax.xml.bind.annotation.XmlRootElement; @XmlRootElement Public classClassroom {Private intClassroomid; PrivateString Classroomname; PrivateStudent Student; Public intGetclassroomid () {returnClassroomid; } Public voidSetclassroomid (intClassroomid) { This. Classroomid =Classroomid; } PublicString Getclassroomname () {returnClassroomname; } Public voidsetclassroomname (String classroomname) { This. Classroomname =Classroomname; } PublicStudent getstudent () {returnstudent; } Public voidsetstudent (Student Student) { This. Student =student; } PublicClassroom (intClassroomid, String classroomname, Student Student) { Super(); This. Classroomid =Classroomid; This. Classroomname =Classroomname; This. Student =student; } PublicClassroom () {Super(); //TODO auto-generated Constructor stub }}
Test:
ImportJavax.xml.bind.JAXBContext;ImportJavax.xml.bind.Marshaller; Public classTest {/** * @paramargs*/ Public Static voidMain (string[] args)throwsexception{//TODO auto-generated Method StubJaxbcontext JBT= Jaxbcontext.newinstance (classroom.class); Classroom CR=NewClassroom (1, "one Shift",NewStudent (10, "Zhang San", 22)); Marshaller Ms=Jbt.createmarshaller (); Ms.marshal (CR, System.out); }}
Result: <?xml version= "1.0" encoding= "UTF-8" standalone= "yes"? ><classroom><classroomid>1</ Classroomid><classroomname> Class A </classRoomName><student><age>22</age><id> 10</id><name> Zhang San </name></student></classRoom>
The main areas of attention in this simple example are: 1. Code in the Test.java
2. Annotated @xmlrootelement in classroom class
To generate a Java object from the generated XML file:
Main code:
String xml = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "standalone=\" yes\ "? ><classroom><classroomid >1</classRoomId><classRoomName> class </classRoomName><student><age>22</age> <id>10</id><name> Zhang San </name></student></classRoom> "; = Jaxbcontext.newinstance (classroom. Class); = Unjbt.createunmarshaller (); = (classroom) Unms.unmarshal (new StringReader (XML)); System.out.println (Uncr.getclassroomid ()+uncr.getclassroomname ());
To convert a Java object to an XML format