Summary study! XML and Java Object Conversions---jdk-brought by JAXB (Java Architecture for XML Binding)

Source: Internet
Author: User

JAXB (Java Architecture for XML Binding) is an industry standard and a technology that can produce Java classes based on XML schemas. In this process, JAXB also provides a way to reverse-generate the Java object tree from the XML instance document, and can re-write the contents of the Java object tree 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 and processing functions in Java applications.

Introduction to Annotations
1) @XmlType
2) @XmlElement
3) @XmlRootElement
4) @XmlAttribute
5) @XmlAccessorType
6) @XmlAccessorOrder (not commonly used)
7) @XmlTransient (not commonly used)
8) @XmlJavaTypeAdapter (not commonly used)

1) @XmlType
@XmlType used in class annotations, often used with @xmlrootelement, @XmlAccessorType.
It has three properties: Name, Proporder, namespace, and only the first two properties that are often used. Such as:

@XmlType (name = "Basicstruct", Proporder = {
"Intvalue",
"Stringarray",
"StringValue"
)

When you use the Proporder property of @xmltype, you must list all the properties in the JavaBean object, or you will get an error.
In the example above, it's okay not to list.

2) @XmlElement
@XmlElement map the properties of Java objects to nodes of XML, and when using @xmlelement, you can change the name of the Java object properties displayed in the XML by the Name property. Such as:

@XmlElement (name= "Address")
Private String youraddress;


3) @XmlRootElement
@XmlRootElement for class-level annotations that correspond to elements of XML, often used with @XmlType and @XmlAccessorType. Such as:

@XmlType
@XmlAccessorType (Xmlaccesstype.field)
@XmlRootElement
public class Address {}

4) @XmlAttribute
@XmlAttribute is used to map the properties of a Java object to an XML property, and you can specify an alias for the generated XML property by using 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 in conjunction with @xmlrootelement, @XmlType. Its property value is 4 enumerated values of Xmlaccesstype, divided by
Not for:
XmlAccessType.FIELD:java all member variables in an object
All member variables in the XmlAccessType.PROPERTY:java object that are accessed through Getter/setter mode
Member variables for 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 elements of XML

Note: The default access level for @XmlAccessorType is Xmlaccesstype.public_member,
Therefore, if the private member variable in the Java object sets the Getter/setter method for the public permission, do not
The @xmlelement and @xmlattribute annotations are used on the private variable, otherwise the same attribute is reported as having two errors in the Java class when the XML is generated by the Java object.

Similarly, if @xmlaccessortype's access rights are Xmlaccesstype.none,
If a @xmlelement or @xmlattribute annotation is used on a member variable in Java,
These member variables can still be mapped to XML files.

6) @XmlAccessorOrder
@XmlAccessorOrder is used to sort the XML elements that are generated by the Java object. It has two attribute values:
Accessororder.alphabetical: Sorting the generated XML elements alphabetically
Xmlaccessorder.undefined: Not sorted

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

8) @XmlJavaTypeAdapter
@XmlJavaTypeAdapter are commonly used when converting more complex objects, such as map types or formatted dates. When using this annotation, you need to write a adapter class to inherit the XMLAdapter abstract class and implement the method inside.

@XmlJavaTypeAdapter (Value=xxx.class), value defines the adapter class for itself

XMLAdapter 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);
}

Code Case:
@XmlRootElement (name = "Opdetail")//root nodeclassOpdetail {@XmlElement//node Element    PrivateRecordInfo RecordInfo;  Public voidSetrecordinfo (RecordInfo recordinfo) { This. RecordInfo =RecordInfo; } @Override PublicString toString () {returnTostringbuilder.reflectiontostring ( This, Tostringstyle.multi_line_style); }}classRecordInfo {@XmlElementPrivateList<fieldinfo>FieldInfo; @XmlAttribute//Node Properties    PrivateString isnew;  Public voidsetisnew (String isnew) { This. isnew =isnew; }     Public voidSetfieldinfo (list<fieldinfo>fieldInfo) {         This. FieldInfo =FieldInfo; } @Override PublicString toString () {returnTostringbuilder.reflectiontostring ( This, Tostringstyle.multi_line_style); }}classFieldInfo {PrivateString Fieldchname; PrivateString Fieldenname; PrivateString fieldcontent;  PublicString Getfieldchname () {returnFieldchname; }     Public voidsetfieldchname (String fieldchname) { This. Fieldchname =Fieldchname; }     PublicString Getfieldenname () {returnFieldenname; }     Public voidsetfieldenname (String fieldenname) { This. Fieldenname =Fieldenname; }     PublicString getfieldcontent () {returnfieldcontent; }     Public voidsetfieldcontent (String fieldcontent) { This. fieldcontent =fieldcontent; } @Override PublicString toString () {returnTostringbuilder.reflectiontostring ( This, Tostringstyle.multi_line_style); }}

Main method Test:

 Public Static voidMain (string[] args)throwsException {opdetail opdetail=NewOpdetail (); RecordInfo RecordInfo=NewRecordInfo (); Recordinfo.setisnew ("New"); List<FieldInfo> FieldInfo =NewArraylist<>(); FieldInfo F1=NewFieldInfo (); F1.setfieldchname ("Area 1"); F1.setfieldenname ("Area1"); F1.setfieldcontent (China); FieldInfo F2=NewFieldInfo (); F2.setfieldchname ("Area 2"); F2.setfieldenname ("Area2"); F2.setfieldcontent (Malaysia);        Fieldinfo.add (F1);        Fieldinfo.add (F2);        Recordinfo.setfieldinfo (FieldInfo);        Opdetail.setrecordinfo (RecordInfo); //Create an output stream       StringWriter sw = new StringWriter (); Try {            //using the transform class that comes with the JDK            Jaxbcontext context = jaxbcontext.newinstance (Opdetail.class);            Marshaller Marshaller = Context.createmarshaller (); //Set EncodingMarshaller.setproperty (marshaller.jaxb_encoding, "GBK"); //do you want to bring <?xml version= "1.0" encoding= "GBK" standalone= "yes"?>Marshaller.setproperty (marshaller.jaxb_fragment, Boolean.false); //Format the XML outputMarshaller.setproperty (Marshaller.jaxb_formatted_output, boolean.true); //convert an object to an XML in the form of an output stream Marshaller.marshal (Opdetail, SW); } Catch(jaxbexception e) {e.printstacktrace (); } System.out.println (sw.tostring ());
/* Output is as follows:

<?xml version= "1.0" encoding= "GBK" standalone= "yes"?>
<opDetail>
<recordinfo isnew= "New" >
<fieldInfo>
<fieldChName> Area 1</fieldchname>
<fieldContent> China </fieldContent>
<fieldEnName>area1</fieldEnName>
</fieldInfo>
<fieldInfo>
<fieldChName> Area 2</fieldchname>
<fieldContent> Malaysia </fieldContent>
<fieldEnName>area2</fieldEnName>
</fieldInfo>
</recordInfo>
</opDetail>

*/

/*converting an XML string into a Java object*/        //String xml = "<?xml version=\" 1.0\ "encoding=\" Gbk\ "standalone=\" yes\ "? ><opdetail><recordinfo& gt;<fieldinfo><fieldchname> Area 1</fieldchname><fieldcontent> China </fieldContent>< Fieldenname>area1</fieldenname></fieldinfo><fieldinfo><fieldchname> Area 2</ Fieldchname><fieldcontent> Malaysia </fieldcontent><fieldenname>area2</fieldenname></        Fieldinfo></recordinfo></opdetail> "; //Jaxbcontext JC = jaxbcontext.newinstance (opdetail.class); //unmarshaller u = Jc.createunmarshaller (); //opdetail o = (opdetail) U.unmarshal (New Streamsource (new StringReader (XML)); //System.out.println (o.tostring ());
/* Output is as follows:

[Email protected] [
[Email protected] [
Fieldinfo=[[email protected][
Fieldchname= Area 1
Fieldenname=area1
Fieldcontent= China
], [email protected][
Fieldchname= Area 2
Fieldenname=area2
Fieldcontent= Malaysia
]]
Isnew=<null>
]
*/

 }

Summary study! XML and Java Object Conversions---jdk-brought by JAXB (Java Architecture for XML Binding)

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.