XML refers to Extensible Markup Language (E
XTensible
MArkup
LAnguage). XML is designed to transmit and store data.
Use third-party packages here Simple-xml-2.7.1.jar
Take a book object as an example, attribute:
ID, title, author list, price
Object Book.java:
PackageCom.newer.xml;ImportJava.io.File;ImportOrg.simpleframework.xml.core.Persister; Public classApp { Public Static voidMain (string[] args) {toXml ();//Toobject (); } Private Static voidToobject () {//input StreamFile File =NewFile ("B.xml"); //Persistence ToolsPersister Persister =NewPersister (); //File---> Object (book.class) Try{ Book book= Persister.read (book.class, file); System.out.println (Book.tostring ()); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Private Static voidtoXml () {book B1=NewBook ("Song of Ice and Fire", "123", 39); B1.authors.add ("George"); B1.authors.add (Martin); B1.authors.add ("Martin 2"); B1.authors.add ("Martin 3"); //DOM (Document Object model), SAX, Simple-xml//Persistence classPersister Persister =NewPersister (); Try{Persister.write (B1,NewFile ("B.xml")); Persister.write (B1, System.out); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
The B.xml file is written here, and the console is also written for easy viewing, and the console output is as follows:
is not like Hypertext language HTML format ~
Run interface, parse function file App.java:
PackageCom.newer.xml;ImportJava.io.File;ImportOrg.simpleframework.xml.core.Persister; Public classApp { Public Static voidMain (string[] args) {toXml ();//Toobject (); } Private Static voidToobject () {//input StreamFile File =NewFile ("B.xml"); //Persistence ToolsPersister Persister =NewPersister (); //File---> Object (book.class) Try{ Book book= Persister.read (book.class, file); System.out.println (Book.tostring ()); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Private Static voidtoXml () {book B1=NewBook ("Song of Ice and Fire", "123", 39); B1.authors.add ("George"); B1.authors.add (Martin); B1.authors.add ("Martin 2"); B1.authors.add ("Martin 3"); //DOM (Document Object model), SAX, Simple-xml//Persistence classPersister Persister =NewPersister (); Try{Persister.write (B1,NewFile ("B.xml")); Persister.write (B1, System.out); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Java objects generate XML and parse XML (book)