Introduction to JAXB, and getting started with JAXB

Source: Internet
Author: User
Tags xml attribute
Introduction ORDER BY:

1. Introduction to JAXB

2. Introduction to the core classes in JAXB and related classes

3. Introduction to common annotations in JAXB

4. Use demo display


First, let's describe what JAXB is.
JAXB (Java architecture for XML Binding) 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. JAXB 2.0 is part of JDK 1.6. We don't need to download a third-party Jar pack to make it easy to convert.


The core classes of JAXB are as follows: three

Jaxbcontext class, is an application portal for managing Xml/java binding information.

This class cannot be created directly, and can only be instantiated Jaxbcontext objects in the following ways:

Static Jaxbcontext

newinstance (Class ... classestobebound)
Obtain a new instance of a Jaxbcontext class.
Static Jaxbcontext newinstance (class[] Classestobebound, map<string,?> properties)
Obtain a new instance of a Jaxbcontext class.
Static Jaxbcontext newinstance (String ContextPath)
Obtain a new instance of a Jaxbcontext class.
Static Jaxbcontext newinstance (String ContextPath, ClassLoader ClassLoader)
Obtain a new instance of a Jaxbcontext class.
Static Jaxbcontext newinstance (String ContextPath, ClassLoader ClassLoader, map<string,?> properties)
Obtain a new instance of a Jaxbcontext class.

Marshaller interface, which serializes Java objects into XML data.

The class is familiar with converting to XML data such as formatted output XML, device XML encoding format, and so on:

Marshaller Marshaller = Context.createmarshaller ();
Marshaller.setproperty (Marshaller.jaxb_formatted_output, true);
Marshaller.setproperty (marshaller.jaxb_encoding, ENCODING);
Marshaller.setproperty (Marshaller.jaxb_fragment, false);


Unmarshaller interface, deserializes XML data into Java objects.

The instance to use to deserialize the Java object:

Unmarshaller Unmarshaller = Context.createunmarshaller ();
t = (t) Unmarshaller.unmarshal (new StringReader (XML));


common annotations used for JAXB are as follows:

@XmlType, the Java class or enumeration type is mapped 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.

1. @XmlType

@XmlType used in annotations of class classes, often in conjunction with @xmlrootelement, @XmlAccessorType. It has three properties: Name, Proporder, namespace, and often uses only the first two properties. Such as:

@XmlType (name = "Basicstruct", Proporder = {
    "intvalue",
    "Stringarray",
    "StringValue"
)
When you use the @xmltype Proporder property, you must list all the properties in the JavaBean object, or you will get an error.
2. @XmlElement

@XmlElement to map the properties of a Java object to a node of XML, you can change the name of the Java object property to appear in the XML using the Name property when you use @xmlelement. such as: @XmlElement (name= "address") private String youraddress; 3. @XmlRootElement

@XmlRootElement for class-level annotations, corresponding to elements of XML, often used with @XmlType and @XmlAccessorType. such as: @XmlType
@XmlAccessorType (Xmlaccesstype.field)
@XmlRootElement
The public class Address {} 4. @XmlAttribute @XmlAttribute properties that map the properties of a Java object to XML, and you can specify an alias for the generated XML property through the Name property. such as: @XmlAttribute (name= "Country")
Private String State; 5. @XmlAccessorType

@XmlAccessorType is used to specify how Java object properties are accessed when an XML file is generated by a Java object. Often used with @xmlrootelement, @XmlType. Its property value is the 4 enumerated values of Xmlaccesstype, respectively:

XmlAccessType.FIELD:java all member variables in the object

XmlAccessType.PROPERTY:java all member variables accessed through Getter/setter in the object

Member variables of all public access rights in the XmlAccessType.PUBLIC_MEMBER:java object and member variables accessed through Getter/setter

All properties of the XmlAccessType.NONE:java object are not mapped to XML elements

Note: The default access level for @XmlAccessorType is xmlaccesstype.public_member, so if the private member variable in the Java object sets the Getter/setter method of the public permission, Do not use @xmlelement and @xmlattribute annotations on private variables, otherwise, when XML is generated by Java objects, the same attribute is reported as having two errors in the Java class. Similarly, if @xmlaccessortype access is xmlaccesstype.none, if @xmlelement or @xmlattribute annotations are used on member variables in Java, these member variables can still be mapped to XML files. 6. @XmlAccessorOrder

@XmlAccessorOrder is used to sort the XML elements generated by the Java object. It has two property values:

Accessororder.alphabetical: Alphabetical order of generated XML elements

Xmlaccessorder.undefined: Not sorted 7. @XmlTransient

@XmlTransient is used to indicate that this property is ignored when XML is mapped by a Java object. That is, this element does not appear in the generated XML file. 8. @XmlJavaTypeAdapter

@XmlJavaTypeAdapter commonly used when converting more complex objects, such as a map type or a formatted date. When using this annotation, you need to write a adapter class to inherit the XMLAdapter abstract class and implement the methods inside.

@XmlJavaTypeAdapter (Value=xxx.class), value for its own defined adapter class

XMLAdapter is as follows:

Public abstract class Xmladapter<valuetype,boundtype> {
    //do-nothing constructor for the derived classes.
    Protected XMLAdapter () {}
    //Convert a value type to a bound type.
    Public abstract Boundtype Unmarshal (valuetype v);
    Convert a bound type to a value type.
    Public abstract valuetype Marshal (Boundtype v);
 }

Demo Demo


Tool class:

Package com.lgy.xml;
Import Java.io.StringReader;

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

Import Javax.xml.bind.Unmarshaller; public class Jaxbutil {/** * JavaBean converted to XML * default encoding UTF-8 * @param obj * @param writer * @re  
    Turn */public static String converttoxml (Object obj) {return converttoxml (obj, "UTF-8"); /** * JavaBean converted to XML * @param obj * @param encoding * @return/public s  
        Tatic string Converttoxml (Object obj, String encoding) {string result = NULL;  
            try {jaxbcontext context = Jaxbcontext.newinstance (Obj.getclass ());  
            Marshaller Marshaller = Context.createmarshaller ();  
            Marshaller.setproperty (Marshaller.jaxb_formatted_output, true);  
            Marshaller.setproperty (marshaller.jaxb_encoding, ENCODING); Marshaller.setproperty (MARSHALLER.JAxb_fragment, false);  
            StringWriter writer = new StringWriter ();  
            Marshaller.marshal (obj, writer);  
        result = Writer.tostring ();  
        catch (Exception e) {e.printstacktrace ();  
    return result; /** * XML converted to JavaBean * @param XML * @param c * @return/@SuppressWarnings  
        ("unchecked") public static <T> T Converytojavabean (String XML, class<t> c) {t = null;  
            try {jaxbcontext context = jaxbcontext.newinstance (c);  
            Unmarshaller Unmarshaller = Context.createunmarshaller ();  
        t = (t) Unmarshaller.unmarshal (new StringReader (XML));  
        catch (Exception e) {e.printstacktrace ();  
    } return t;
 }  
}

Simple Type:

Package com.lgy.xml;

Import Java.util.Date;
Import Javax.xml.bind.annotation.XmlAccessType;
Import Javax.xml.bind.annotation.XmlAccessorType;
Import Javax.xml.bind.annotation.XmlAttribute;
Import javax.xml.bind.annotation.XmlElement;
Import javax.xml.bind.annotation.XmlRootElement;

Import Javax.xml.bind.annotation.XmlType; @XmlAccessorType (Xmlaccesstype.field) @XmlRootElement (name= "Xmldemo") @XmlType (Proporder = {"Author", "Calendar", "

	Price '} ' public class Xmldemo {@XmlElement (required = true) Private String author;

	@XmlElement (name = "Price_1", required = true) private float price;

	@XmlElement private Date Calendar;

	@XmlAttribute private Integer ID;
	Public String Getauthor () {return author;
	} public void Setauthor (String author) {this.author = author;
	public float GetPrice () {return price;
	public void Setprice (float price) {this.price = Price;
	Public Date Getcalendar () {return calendar;
	} public void Setcalendar (Date calendar) {	This.calendar = Calendar;
	Public Integer GetId () {return id;
	The public void SetId (Integer id) {this.id = ID; @Override public String toString () {return "Xmldemo [author=] + author +", price= "+ Price +", calendar= "+ Cale"
	Ndar + ", id=" + ID + "]";
 }
}

Complex Type:

Package com.lgy.xml;

Import java.util.List;
Import Javax.xml.bind.annotation.XmlAccessType;
Import Javax.xml.bind.annotation.XmlAccessorType;
Import Javax.xml.bind.annotation.XmlAttribute;
Import javax.xml.bind.annotation.XmlElement;
Import javax.xml.bind.annotation.XmlRootElement;
Import Javax.xml.bind.annotation.XmlType; @XmlAccessorType (Xmlaccesstype.field) @XmlRootElement (name= "Generators") @XmlType (Proporder = {"Generatorsgroups"}
	
	public class Generators {@XmlAttribute private Integer ID;

	@XmlElement (required = true) private list<generatorsgroup> generatorsgroups;
	Public Integer GetId () {return id;
	The public void SetId (Integer id) {this.id = ID;
	Public list<generatorsgroup> getgeneratorsgroups () {return generatorsgroups; } public void Setgeneratorsgroups (list<generatorsgroup> generatorsgroups) {this.generatorsgroups = GeneratorsGr
	oups; @Override public String toString () {return "generators [id= + ID +", generatorsgroupS= "+ generatorsgroups +"];
 }
	
}

Package com.lgy.xml;

Import Javax.xml.bind.annotation.XmlAccessType;
Import Javax.xml.bind.annotation.XmlAccessorType;
Import javax.xml.bind.annotation.XmlElement;
Import Javax.xml.bind.annotation.XmlType;

@XmlAccessorType (Xmlaccesstype.field)
@XmlType (Proporder = {"Test"}) public
class Generatorsgroup {
	@ XmlElement (required = true)
	private String test;

	Public String Gettest () {return
		test;
	}

	public void Settest (String test) {
		this.test = test;
	}

	@Override public
	String toString () {return
		"Generatorsgroup [test=" + Test + "]";
	}
	
	
}


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.