Translate objects into XML in Java (implemented with JDK)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.