Java XML operations-basic use of JAXB

Source: Internet
Author: User

JAXB is mainly used to implement serialization and deserialization between objects and XML. We will not talk much about JAXB, here we will mainly summarize the basic usage and some precautions. First, we will define two sample classes ClassA and ClassB for subsequent examples to demonstrate how to copy the code 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 voi D setClassAName (String classAName) {this. classAName = classAName;} public ClassB getClassB () {return classB;} public void setClassB (ClassB classB) {this. classB = classB ;}} copy code 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 S Tring getClassBName () {return classBName;} public void setClassBName (String classBName) {this. classBName = classBName;} copy the XmlUtil code used for serialization 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 (); extends aller marshal Ler = context. createMarshaller (); extends aller. setProperty (exploraller. JAXB_ENCODING, "UTF-8"); // encoding format: marshaller. setProperty (exploraller. JAXB_FORMATTED_OUTPUT, true); // whether to format the generated xml string marshaller. setProperty (exploraller. JAXB_FRAGMENT, false); // whether to omit the xm header declaration information StringWriter writer = new StringWriter (); extends aller. marshal (obj, writer); return writer. toString ();} catch (Exception e) {throw new runtime=t Ion (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 () ;}}: copy the code package cn. lzrabbit; public c Lass 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) ;}} the output result of the copied code is as follows: copy the Code <? 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> copy the code. Pay attention to the following classes to be serialized and add the @ XmlRootElement annotation, otherwise, an error will be reported (the error prompt is clear and will not be posted here). getter and setter will be serialized by default when JAXB serializes XML, and the getter and setter must be paired before being serialized, the default serialized class and attribute names are converted to lowercase by default. To control the attribute names, use @ XmlElement (name = "ClassAId") on getter or setter to specify the names, note that @ XmlElement can be placed on both getter and setter, but only one That is to say, you cannot use the @ XmlElement Annotation on both getter and setter to control the root node name? Use @ XmlRootElement to specify the name attribute, for example, how to add a namespace using @ XmlRootElement (name = "ClassA. lzrabbit ") How to precisely control the namespace attribute? automatic conversion of each attribute name JAXB to the first letter in lower case may lead to unexpected attribute names, if it is not too troublesome, set @ XmlElement (name = "") for each attribute ""), to save trouble, how can I use the Field for serialization instead of adding @ XmlAccessorType (XmlAccessType) to the class to be used by setter and getter. FIELD) annotation, and is set to XmlAccessType. FIELD, @ XmlAccessorType (XmlAccessType. FIELD) annotation, because this allows you to precisely control the name of each element without setting each attribute. @ XmlElement (name = "") annotation. Of course, you can also use the @ XmlElement Annotation on the Field. The following shows the sample Code View Code after using the annotation above to output xml as the copy Code. <? 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> copy the code here. Next, write down the processing of the default namespace and the custom namespace prefix. If you think this article is not bad, click the recommendation in the lower right corner, with your support, you can inspire the author's enthusiasm for writing. Thank you very much. If you have any questions, you can contact me via lzrabbit@126.com.

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.