Java using JAXB Operations XML sample _java

Source: Internet
Author: User
Tags lowercase serialization

First, define two sample class CLASSA,CLASSB for subsequent sample demonstrations

Copy Code code as follows:

Package cn.lzrabbit;

public class ClassA {
private int classaid;
Private String Classaname;

Private CLASSB CLASSB;

public int Getclassaid () {
return classaid;
}

public void Setclassaid (int classaid) {
This.classaid = Classaid;
}

Public String Getclassaname () {
return classaname;
}

public void Setclassaname (String classaname) {
This.classaname = Classaname;
}

Public ClassB Getclassb () {
return CLASSB;
}

public void Setclassb (ClassB classb) {
THIS.CLASSB = CLASSB;
}
}

ClassA

Copy Code code as follows:

Package cn.lzrabbit;

public class ClassB {
private int classbid;
Private String Classbname;

public int getclassbid () {
return classbid;
}

public void setclassbid (int classbid) {
This.classbid = Classbid;
}

Public String Getclassbname () {
return classbname;
}

public void Setclassbname (String classbname) {
This.classbname = Classbname;
}
}

ClassB

Xmlutil for serialization

Copy Code code as follows:

Package cn.lzrabbit;

Import Java.io.StringReader;
Import Java.io.StringWriter;

Import javax.xml.bind.*;

public class Xmlutil {

public static String ToXML (Object obj) {
try {
Jaxbcontext context = Jaxbcontext.newinstance (Obj.getclass ());

Marshaller Marshaller = Context.createmarshaller ();
Marshaller.setproperty (marshaller.jaxb_encoding, "UTF-8");///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 XM header declaration information
StringWriter writer = new StringWriter ();
Marshaller.marshal (obj, writer);
return writer.tostring ();
catch (Exception e) {
throw new RuntimeException (e);
}
}

@SuppressWarnings ("Unchecked")
public static <T> T fromxml (String XML, class<t> valuetype) {
try {
Jaxbcontext context = Jaxbcontext.newinstance (valuetype);
Unmarshaller Unmarshaller = Context.createunmarshaller ();
Return (T) Unmarshaller.unmarshal (new StringReader (XML));
catch (Exception e) {
throw new RuntimeException (E.getmessage ());
}
}
}

Xmlutil

The call is as follows:

Copy Code code as follows:

Package cn.lzrabbit;

public class Mainrun {

/**
* @param args
*/
public static void Main (string[] args) {

CLASSB CLASSB = new ClassB ();
Classb.setclassbid (22);
Classb.setclassbname ("B2");

ClassA ClassA = new ClassA ();
Classa.setclassaid (11);
Classa.setclassaname ("A1");
CLASSA.SETCLASSB (CLASSB);

System.out.println (Xmlutil.toxml (ClassA));
}

}

Mainrun

The output results are as follows:

Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?>
<classA>
<classAId>11</classAId>
<classAName>A1</classAName>
<classB>
<classBId>22</classBId>
<classBName>B2</classBName>
</classB>
</classA>

Here are the following points to note

1 The class to be serialized plus @XmlRootElement annotation, or it will be an error (the wrong hint is very clear, here is not posted)

2JAXB serializes the getter and setter by default when serializing XML, and the getter and setter must appear in pairs before they are serialized

3 property names, default serialized class and property names are converted to lowercase by default, and if you need to control the property name you need to use @XmlElement (name= "Classaid") on the getter or setter to specify the name, Note here that the @xmlelement is placed on the getter or setter, but only one can be placed, that is, the @xmlelement annotation cannot be used simultaneously on the getter and the setter

4 How do I control the root node name?
Use @xmlrootelement to specify the Name property, such as @xmlrootelement (name= "ClassA")

5 How to add namespaces
Specify namespace properties using @xmlrootelement (namespace= "Cn.lzrabbit")

6 How to control each property name precisely
The automatic conversion of JAXB to the lowercase will cause unexpected property names to appear, not too troublesome. Set @xmlelement (name= "") for each property, if you want to use field

7 How to implement serialization using field fields instead of setter and getter
Add the @xmlaccessortype (Xmlaccesstype.field) annotation to the class to be used, and specify Xmlaccesstype.field, where @xmlaccessortype is strongly recommended ( Xmlaccesstype.field) annotation, because you can precisely control the name of each element without having to set @xmlelement (name= "") annotations for each attribute, and of course you can use @xmlelement annotations on the FIELD

The following is a code example using the following annotation

Copy Code code as follows:

@XmlRootElement (namespace= "Cn.lzrabbit")
@XmlAccessorType (Xmlaccesstype.field)
public class ClassA {
private int classaid;

@XmlElement (name= "Classaname")
Private String Classaname;

Private CLASSB CLASSB;

public int Getclassaid () {
return classaid;
}
public void Setclassaid (int classaid) {
This.classaid = Classaid;
}

Public String Getclassaname () {
return classaname;
}

public void Setclassaname (String classaname) {
This.classaname = Classaname;
}

Public ClassB Getclassb () {
return CLASSB;
}

public void Setclassb (ClassB classb) {
THIS.CLASSB = CLASSB;
}
}

@XmlRootElement
@XmlAccessorType (Xmlaccesstype.field)
public class ClassB {
private int classbid;
Private String Classbname;

public int getclassbid () {
return classbid;
}

public void setclassbid (int classbid) {
This. Classbid = Classbid;
}

Public String Getclassbname () {
return classbname;
}

public void Setclassbname (String classbname) {
This. Classbname = Classbname;
}
}

Output XML is

Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?>
<ns2:classa xmlns:ns2= "Cn.lzrabbit" >
<classAId>11</classAId>
<ClassAName>A1</ClassAName>
<classB>
<ClassBId>22</ClassBId>
<ClassBName>B2</ClassBName>
</classB>
</ns2:classA>

PS: Here again for you to provide several online tools on XML operations for your reference to use:

Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson

Online format xml/on-line compression of XML:
Http://tools.jb51.net/code/xmlformat

XML Online compression/formatting tool:
http://tools.jb51.net/code/xml_format_compress

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.