in Java, there are many ways to convert an object into an XML file, and with dom4j, you can serialize to XML, and with some tool classes in the Simpleframework framework, you can simply sequence objects into XML files. Interested programs apes can search the web for concrete methods, and let's look at how the tools in the JDK (1.5) are implemented to convert an object into XML form.
Package Javatoxml;import Java.io.stringwriter;import Javax.xml.bind.jaxbcontext;import Javax.xml.bind.jaxbexception;import Javax.xml.bind.marshaller;import javax.xml.bind.annotation.xmlrootelement;@ Xmlrootelement (name = "Jdktoxml") public class TOXMLWIDTHJDK {private int id; private String name; public int getId () {///must have, the return ID is automatically called when you turn to XML; } public void setId (int id) {this.id = ID; The public String GetName () {//must have, and the return name is automatically called when you turn to XML; } public void SetName (String name) {this.name = name; } public static void Main (string[] args) {TOXMLWIDTHJDK tx = new TOXMLWIDTHJDK (); Tx.setid (24); Tx.setname ("chenleixing"); StringWriter SW = new StringWriter (); Jaxbcontext Jbc=null; Marshaller mar=null;try {JBC = Jaxbcontext.newinstance (Tx.getclass ());//Incoming object type to be converted to XML mar = Jbc.createmarshaller (); Mar.marshal (TX, SW);} catch (Jaxbexception e) {//TODO auto-generated catch Blocke.printstacKtrace ();} System.out.println ("The content of the XML file that will be written is:" +sw.tostring ()); }}
The output is:
The content of the XML file that will be written is: <?xml version= "1.0" encoding= "UTF-8" standalone= "yes"? ><jdktoxml><id>24</id ><name>chenleixing</name></JDKtoXml>
Translate objects into XML in Java (implemented with JDK)