Jaxb:xml and Java Object Transfer

Source: Internet
Author: User
Tags map class

Jaxbcontext generating XML file or Java class object conversion annotations
JAXB provides a quick and easy way to convert Java objects to and from XML. In Jax-WS (One of Java's WebService specifications), JDK1.6 comes with version jax-ws2.1, with the underlying support being JAXB.
JAXB can implement the conversion of Java objects to XML, in JAXB, the process of converting a Java object to XML is called Marshal, and the process of converting XML to a Java object is called Unmarshal. We can bind a Java object to a piece of XML by annotating it in a Java class, that is, annotating the Java class with annotations that define how the class is converted to XML, how it is transformed, and how an XML is parsed into the object defined by the class. You can also use the JAXB XJC tool to implement Java object binding with XML by defining the schema.
Here's a look at how to complete the Marshal and unmarshal process by annotating annotations.
First look at a small example
Define a Java class

Package com.my.test; Import javax.xml.bind.annotation.XmlRootElement;        @XmlRootElement public class People {public String id = "11111";        Public String name = "Name";    public int age = 26; }

Java to XML (Marshal)

package com.my.test; import javax.xml.bind.jaxbcontext;    import  javax.xml.bind.jaxbexception;    import javax.xml.bind.marshaller;     public class Java2XML {        /**         *  @param  args        *   @throws  JAXBException         */        public static void main (String[] args)  throws  jaxbexception {            jaxbcontext  Context = jaxbcontext.newinstance (People.class);                    Marshaller marshaller =  Context.createmarshaller ();              marshaller.setproperty (Marshaller.JAXB_ENCODING, "gb2312 ");//Encoding Format         marshaller.setproperty (marshaller.jaxb_formatted_ Output, true);//whether to format the generated XML string         marshaller.setproperty ( Marshaller.jaxb_fragment, false);//whether to omit the XML header information (<?xml version= "1.0"  encoding= "gb2312"   Standalone= "yes"?>)         People people = new  People ();             marshaller.marshal (People,  system.out);         }      }

XML to Java (unmarshal)

package com.my.test;    import java.io.file;    import  javax.xml.bind.jaxbcontext;    import javax.xml.bind.jaxbexception;     import javax.xml.bind.Unmarshaller;    import org.xml.sax.SAXException;     public class XML2Java {         /**        *  @param  args         *  @throws  jaxbexception         * @ throws jaxbexception         *  @throws   saxexception         */        Public static void main (String[] args)  throws JAXBException {              jaxbcontext context = jaxbcontext.newinstance (People.class);             unmarshaller unmarshaller =  context.createunmarshaller ();             File file = new file ("Src/people.xml");             People people =  (People) Unmarshaller.unmarshal (file);             system.out.println (people.id);             system.out.println (People.name);             system.out.println (people.age);         }    }

In fact, marshal and unmarshal process is not complicated, only need to get Marshaller or Unmarshaller object from Jaxbcontext, you can let JAXB help us to convert. The main aspect of what we need to do is to define a rule that tells Jaxb how to convert a class to XML in what format.

Here are some of the main annotations in JAXB.
@XmlRootElement Map a Java class to the root node of an XML, parameters:
Name to define this root node
namespace defines this root node namespace

@XmlAccessorType define what types of mappings in this class need to be mapped to XML. Can receive four parameters, respectively:
Xmlaccesstype.field: Mapping All fields in this class to XML
Xmlaccesstype.property: Mapping properties in this class (Get/set method) to XML
Xmlaccesstype.public_member: Maps the field or property of all public in this class to XML at the same time (default)
Xmlaccesstype.none: Not mapped

@XmlElement a node that specifies a field or Get/set method to map to XML. For example, when the xmlaccessortype of a class is labeled as a property, the annotation is annotated on a field that does not have a Get/set method to map the field to XML. Parameters:

DefaultValue specifying a node default value
Name specifies the node name
Namespace specifying a node namespace
Required whether it must (default false)
nillable Whether the field contains a nillable= "true" property (False by default)
Type defines the association types for this field or property

@XmlAttribute Specify a field or Get/set method to map to the attributes of the XML. Parameters:

Name Specifies the property name
Namespace specifying a property namespace
Whether the required must be (false by default)

@XmlTransient Define a field or property that does not need to be mapped to XML. For example, when a class's xmlaccessortype is labeled as a property, the annotation is annotated on the field of a Get/set method, and the attribute is not mapped.

@XmlType Some related rule parameters for defining mappings:

Proporder specifying the order of nodes when mapping XML
FACTORYCLASS Specifies the factory class required to generate the Map class instance when Unmarshal is specified, which defaults to the class itself
FactoryMethod factory methods for specifying factory classes
Name defines the names of the type in the XML Schema
Namespace specifying namespaces in the schema

@XmlElementWrapper define a parent node for an array element or collection element. For example, an element in a class is a list items, and if you do not add this annotation, the element is mapped to
<items>...</items>
<items>...</items>
This form, this annotation can be wrapped in this element, such as:
@XmlElementWrapper (name= "items")
@XmlElement (name= "item")
public List items;
Such an XML style will be generated:
<items>
<item>...</item>
<item>...</item>
</items>

@XmlJavaTypeAdapter customize an adapter that maps a field or property to XML. For example, if a class contains an interface, we can define an adapter (inherited from the Javax.xml.bind.annotation.adapters.XmlAdapter Class) to specify how the interface maps to XML.

@XmlSchema Configure the namespace of the entire package, this annotation needs to be placed in the Package-info.java file.

JAXB Encoding:
Jaxbcontext Jaxbcontext = jaxbcontext.newinstance (clazz);
Unmarshaller Unmarshaller = Jaxbcontext.createunmarshaller ();
InputStreamReader reader=new InputStreamReader (InputStream, "GBK");//Modify the encoding here
return Unmarshaller.unmarshal (reader);

Jaxb:xml and Java Object Transfer

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.