Import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Article {private string title; private string author; private string email; private string date;
@Override public String toString () { return "article [title=" + title + ", author=" + author + ", email=" + Email + ", date=" + Date + "]"; } Public String GetTitle () { return title; } public void Settitle (String title) { this.title = title; } Public String Getauthor () { return author; } public void Setauthor (String author) { this.author = author; } Public String Getemail () { return email; } public void Setemail (String email) { This.email = email; } Public String getDate () { return date; } public void SetDate (String date) { this.date = date; }}
Import Java.io.file;import Javax.xml.bind.jaxbcontext;import Javax.xml.bind.jaxbexception;import javax.xml.bind.marshaller;//convert Java object to Xmlpublic class Jaxbarticle {public static void Main (string[] args) throws jaxbexception { //Create XML Document object, save path to e:\\test.xml file File=new file ("D:\\test.xml"); Declaring Jaxbcontext Context objects
Jaxbcontext context=jaxbcontext.newinstance (article.class); Creates a Java object that is converted to XML through a context object Marshaller; Marshaller M=context.createmarshaller (); Create the data required in XML article article=new article (); Article.settitle ("The Little Prince"); Article.setauthor ("Antoine De Saint-Hens Exoupes"); Article.setdate ("20180901"); Article.setemail ("[email protected]"); Convert Java objects to XML M.marshal (article,file); SYSTEM.OUT.PRINTLN (article); }}
Import Java.io.file;import Javax.xml.bind.jaxbcontext;import Javax.xml.bind.jaxbexception;import javax.xml.bind.unmarshaller;//convert XML to Javapublic class Jaxbaticlexml {public static void Main (string[] args) Throws Jaxbexception { //Create Document object found in D-disk test.xml file file=new files ("D:\\test.xml"); Declares the Jaxbcontext context object jaxbcontext context=jaxbcontext.newinstance (article.class); Creates a Unmarshaller () object that converts an XML file to Java through a context object Unmarshaller U=context.createunmarshaller (); Convert the XML file to Java article article= (article) u.unmarshal (file); The ToString method uses the difference between before and after article System.out.println (article);} }
Convert XML to Java (1.Java object converted to XML (Marshaller) 2.XML to Java Object (Unmarshaller))