Java objects and XML are __xml to each other

Source: Internet
Author: User
Tags ming xml attribute

JAXB (Java architecture for XML Binding) is an industry standard and is a technology that can generate Java classes from XML schemas. In this process, JAXB also provides a way to reverse-generate the XML instance documents to the Java object Tree and to write the contents of the Java object Tree back to the XML instance document. On the other hand, JAXB provides a quick and easy way to bind XML schemas to Java representations, making it easy for Java developers to combine XML data with processing functions in Java applications.
The most important class and interface for JAXB related to the JDK: (from the Baidu Encyclopedia Jaxb)
Jaxbcontext class, is an application portal for managing Xml/java binding information.
Marshaller interface, which serializes Java objects into XML data.
Unmarshaller interface, deserializes XML data into Java objects.
Important annotation related to JAXB in JDK: (from Baidu Encyclopedia Jaxb)
@XmlType to map a Java class or enumeration type to an XML Schema type
@XmlAccessorType (Xmlaccesstype.field), which controls the serialization of a field or property. field indicates that JAXB will automatically bind each non-static (static), non transient (@xmltransient-labeled) field in the Java class to XML. Other values are Xmlaccesstype.property and Xmlaccesstype.none.
@XmlAccessorOrder, controls the sorting of properties and fields in the JAXB binding class.
@XmlJavaTypeAdapter, use a custom adapter (that is, extend the abstract class XMLAdapter and overwrite the marshal () and Unmarshal () methods) to serialize the Java class to XML.
@XmlElementWrapper, for an array or collection (that is, a member variable that contains multiple elements), generates an XML element (called a wrapper) that wraps the array or collection.
@XmlRootElement to map a Java class or enumeration type to an XML element.
@XmlElement, a property of a Java class is mapped to an XML element with the same name as a property.
@XmlAttribute, a property of a Java class is mapped to an XML attribute with the same name as a property.
In the above note, the most used is @xmltype, @XmlAccessorType, @XmlRootElement.
Reasons for using JAXB:
1, there are sometimes a lot of XML files in the project, but if you can manipulate them through the object, it will reduce many operational problems and be more in line with the programmer's coding.
2, in the project, there are times when you encounter data from a lot of entity classes in a page, and sometimes some data is not required, that is, you can write these entity classes through a DTO, but sometimes you need to store these dto in advance, not in a database, so there are two ways Can be stored in memory or stored on a hard disk, and can be stored in memory by converting Java objects to XML file stores, or to a string type.
3, give a scene, for example, a page has many modules, but these modules are part of a whole module, when the user has to operate several modules, but the operation of the data is not the final data, then the first time to save the current page of data (done), Then go to other pages and then move to this page, then the data in the previous page should still exist, users can easily view. However, because of the large number of modules, if the previous deposit into the database will cause waste, because it is not the final save effect, and when the user wants to save, this time to save the final data to the database. There is a lot of temporary data to be used in this process, and the best way to solve this problem is to save the current data in the page with XML.
In this article, first I give an object to the conversion of XML, and then, in the concept of the module to explain the three kinds of scenarios, of course, the code is not difficult, very simple simulation, the concept of the project will be more complex than this, there will be specialized complex this process code writing. So, I just want to make a comment, can let the reader as far as possible to have this kind of thought, when writing the project time if has encountered this kind of situation, can carry on the thought migration very well.

Pojo

Package Com.ming.pojo;

Import java.io.Serializable;
Import Javax.xml.bind.annotation.XmlAccessType;
Import Javax.xml.bind.annotation.XmlAccessorType;
Import javax.xml.bind.annotation.XmlRootElement;

Import Javax.xml.bind.annotation.XmlType; @XmlAccessorType (Xmlaccesstype.field) @XmlRootElement (name = "Phone") @XmlType (Proporder = {"UserId", "Phone"}) public
    Class Phone implements Serializable {/** * * */private static final long serialversionuid = 1L;
    Private long userId;

    Private String phone;
        Public phone () {} public phone (long userId, String Phone) {super ();
        This.userid = userId;
    This.phone = phone;
    Public long GetUserID () {return userId;
    } public void Setuserid (long userId) {this.userid = UserId;
    Public String Getphone () {return phone;
    public void Setphone (String phone) {this.phone = phone; @Override Public String TostriNg () {return "phone [userid=" + UserId + ", phone=" + Phone + "]";
 }

}
Package Com.ming.pojo;
Import java.io.Serializable;

Import java.util.List;
Import Javax.xml.bind.annotation.XmlAccessType;
Import Javax.xml.bind.annotation.XmlAccessorType;
Import javax.xml.bind.annotation.XmlRootElement;

Import Javax.xml.bind.annotation.XmlType; The @XmlAccessorType (Xmlaccesstype.field) @XmlRootElement (name = "User") @XmlType (Proporder = {"UserId", "UserName", " PassWord "," Phones "}) public class User implements Serializable {/** * */private static final long SE
    Rialversionuid = 1858480386705537937L;
    Private long userId;
    Private String UserName;
    Private String PassWord;

    Private list<phone> phones;
        Public user () {} public user (long userId, String userName, String passWord) {This.userid = UserId;
        This.username = UserName;
    This.password = PassWord;
    Public long GetUserID () {return userId;
    } public void Setuserid (long userId) {this.userid = UserId;

}    Public String GetUserName () {return userName;
    } public void Setusername (String userName) {this.username = UserName;
    Public String GetPassword () {return passWord;
    } public void SetPassword (String passWord) {This.password = PassWord;
    Public list<phone> Getphones () {return phones;
    public void Setphones (list<phone> phones) {this.phones = phones; @Override public String toString () {return "User [userid=" + UserId + ", username=" + UserName + ", PA
    Ssword= "+ PassWord +", phones= "+ phones +"];
 }

}

Core

Package com.ming.util;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.io.StringReader;

Import Java.io.StringWriter;
Import Javax.xml.bind.JAXBContext;
Import javax.xml.bind.JAXBException;
Import Javax.xml.bind.Marshaller;

Import Javax.xml.bind.Unmarshaller; /** * encapsulates the code converted to object,object XML into XML * * @author Ming */public class Xmlutil {/** * converts objects directly XML output of type String * * @param obj * @return/public static String converttoxml (Object obj)  
        {///Create output stream StringWriter SW = new StringWriter ();  

            try {///Jaxbcontext context = Jaxbcontext.newinstance (Obj.getclass ()) by using the transform class that is brought in the JDK;  
            Marshaller Marshaller = Context.createmarshaller ();   
          Format XML output Marshaller.setproperty (Marshaller.jaxb_formatted_output, boolean.true);  An XML Marshaller.marshal (obj, SW) that converts an object to an output stream form;  
        catch (Jaxbexception e) {e.printstacktrace ();  
    return sw.tostring ();  /** * Converts an object to an XML file based on a path * * @param obj * @param path * @return/Public static void Converttoxml (Object obj, String path) {try {//Jaxbcon with a transform class from the JDK  

            Text context = Jaxbcontext.newinstance (Obj.getclass ());  
            Marshaller Marshaller = Context.createmarshaller ();   
            Format XML output Marshaller.setproperty (Marshaller.jaxb_formatted_output, boolean.true);  
            An XML//create output stream that converts an object to an output stream FileWriter FW = null;  
            try {fw = new FileWriter (path);  
            catch (IOException e) {e.printstacktrace ();  
        } marshaller.marshal (obj, FW); } CATCH (jaxbexception e) {e.printstacktrace (); @SuppressWarnings ("unchecked")/** * Convert string XML to object/public static object C  
        Onvertxmlstrtoobject (Class clazz, String xmlstr) {Object xmlobject = null;  
            try {jaxbcontext context = jaxbcontext.newinstance (clazz);  
            The core interface for converting XML into objects Unmarshaller Unmarshaller = Context.createunmarshaller ();  
            StringReader sr = new StringReader (XMLSTR);  
        Xmlobject = Unmarshaller.unmarshal (SR);  
        catch (Jaxbexception e) {e.printstacktrace ();  
    return xmlobject; @SuppressWarnings ("unchecked")/** * Converts a file type of XML to an object/public static object Convertxmlf  
        Iletoobject (Class clazz, String xmlpath) {Object xmlobject = null;  
            try {jaxbcontext context = jaxbcontext.newinstance (clazz); UnmarShaller Unmarshaller = Context.createunmarshaller ();  
            FileReader FR = null;  
            try {fr = new FileReader (Xmlpath);  
            catch (FileNotFoundException e) {e.printstacktrace ();  
        } xmlobject = Unmarshaller.unmarshal (FR);  
        catch (Jaxbexception e) {e.printstacktrace ();  
    return xmlobject;  
 }  
}

Test:

Package com.ming;

Import java.util.ArrayList;
Import java.util.Date;
Import java.util.List;

Import Com.ming.pojo.Phone;
Import Com.ming.pojo.User;
Import Com.ming.util.XMLUtil;

public class Test {public
    static void Main (string[] args) {
        //Create the object to be converted
        User user = new User (1, "Ming", "1234 ");
        Phone phone=new Phone (1, "12345678910");
        Phone phone1=new Phone (1, "12345678911");
        List<phone> phones=new arraylist<phone> ();
        Phones.add (phone);
        Phones.add (phone1);
        User.setphones (phones);
        SYSTEM.OUT.PRINTLN ("---Converts an object to a string-type XML Start---");
        Converts an object to string-type XML
        string str = xmlutil.converttoxml (user);
        Output
        System.out.println (str);

        User user1= (user) Xmlutil.convertxmlstrtoobject (user.class, str);
        System.out.println (user1);

    }

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.