Enables transformations between Java object Objects and XML using Marshaller and Unmarshaller
First, create a simple boy object
@XmlRootElement (name= "Root")
@XmlAccessorType (xmlaccesstype.property) public
class Boy {
private String name = "AA";
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
}
where @xmlrootelement (name= "root") indicates the root element of the XML (name= "root") this is the same element that redefined the XML file, and if there is no such name definition, the XML root element defaults to the object name
The object is then converted to XML through the Marshaller class implementation, and the Unmarshaller class is used to convert between XML and classes
public class Jaxbtest {public
static void Main (string[] args) throws Jaxbexception {
Jaxbcontext context = Jaxbco Ntext.newinstance (boy.class);
Marshaller Marshaller = Context.createmarshaller ();
Unmarshaller Unmarshaller = Context.createunmarshaller ();
System.out.println ("----------marshaller--------------");
Boy Boy = new Boy ();
Marshaller.marshal (Boy, System.out);
System.out.println ("\ n----------unmarshaller--------------");
convert XML to corresponding Java object
String xml = "<Root><name>aa</name></Root>";//the label name must be consistent with the properties of the boy object
Boy B = (Boy) Unmarshaller.unmarshal (new StringReader (XML));
System.out.println (B.getname ());
}
Finally convert print results
----------Marshaller--------------
<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?><root><name>aa</name></root>
----------Unmarshaller--------------
Aa