Using JAXB to convert instances of Java objects and XML strings to each other

Source: Internet
Author: User

Test class:

Package Com.yanek.test;import Java.util.arraylist;import Java.util.list;import Com.yanek.test.jaxbutil.collectionwrapper;public class Test {/** * @param args */public static void main (string[] args) {/ /Create Java Object Hotel Hotel=new (); Hotel.setid (1); Hotel.setname ("name1"); Roomtypevo t1=new Roomtypevo () t1.setprice ("a") T1.settypeid (1); T1.settypename ("typename1"); Roomtypevo t2=new Roomtypevo () t2.setprice ("a") T2.settypeid (2); T2.settypename ("typename2"); List<roomtypevo> roomtypevos=new arraylist<roomtypevo> (); Roomtypevos.add (t1); Roomtypevos.add (T2); Hotel.setroomtypevos (Roomtypevos);//Convert Java object to XML string Jaxbutil Requestbinder = new Jaxbutil ( Hotel.class,collectionwrapper.class); String retxml = Requestbinder.toxml (hotel, "Utf-8"); SYSTEM.OUT.PRINTLN ("xml:" +retxml);//Convert XML string to Java object Jaxbutil Resultbinder = new Jaxbutil (Hotel.class, Collectionwrapper.class); Hotel hotelobj = Resultbinder.fromxml (retxml); System.out.println ("Hotelid:" +hotelobj.getid ()); System.out.println ("Hotelname:" +hoTelobj.getname ()); for (Roomtypevo roomTypeVO:hotelObj.getRoomTypeVOs ()) {System.out.println ("Typeid:" + Roomtypevo.gettypeid ()); System.out.println ("Typename:" +roomtypevo.gettypename ());}}}


The output is as follows:

Xml:<?xml version= "1.0" encoding= "Utf-8" standalone= "yes"? >


Related classes:

Package Com.yanek.test;import Java.util.list;import Javax.xml.bind.annotation.xmlattribute;import Javax.xml.bind.annotation.xmlelement;import Javax.xml.bind.annotation.xmlelementwrapper;import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement (name = "Hotel") public class Hotel {@XmlElementWrapper (name = "Roomtypevos") @XmlElement (name = "Roomtypevo") public list<roomtypevo> Getroomtypevos () {return roomtypevos;} public void Setroomtypevos (list<roomtypevo> roomtypevos) {roomtypevos = Roomtypevos;} Private list<roomtypevo> roomtypevos;/////@XmlElement (name = "id") @XmlAttribute (name = "id") public int getId () { return ID;} public void setId (int id) {this.id = ID;} @XmlElement (name = "name") public String GetName () {return name;} public void SetName (String name) {this.name = name;} private int id;private String name;} Package Com.yanek.test;import Javax.xml.bind.annotation.xmlattribute;import javax.xml.bind.annotation.XmlElement; public class Roomtypevo {//@XmlElement (name = "TYpeid ") @XmlAttribute (name =" typeID ") public int GetTypeId () {return typeid;} public void Settypeid (int typeid) {This.typeid = typeID;} @XmlElement (name = "TypeName") public String Gettypename () {return typename;} public void Settypename (String typename) {this.typename = typename;} @XmlElement (name = ' price ') public String GetPrice () {return price;} public void Setprice (String price) {this.price = Price;} private int typeid;private string typename;private string price;}

JAXB Simple Tool Class:

Package Com.yanek.test;import Java.io.stringreader;import Java.io.stringwriter;import java.util.Collection;import Javax.xml.bind.jaxbcontext;import Javax.xml.bind.jaxbelement;import Javax.xml.bind.jaxbexception;import Javax.xml.bind.marshaller;import Javax.xml.bind.unmarshaller;import javax.xml.bind.annotation.XmlAnyElement; Import Javax.xml.namespace.qname;import org.apache.commons.lang.stringutils;/** * implemented with Jaxb2.0 Xml<->java The binder for object. * * Special support for the root object is the list case. * * @author */public class Jaxbutil {//Multithreading secure context.private jaxbcontext jaxbcontext;/** * @param types * all required The type of the root object to serialize. */public jaxbutil (class<?> ... types) {try {Jaxbcontext = jaxbcontext.newinstance (types);} catch (Jaxbexception e) {throw new RuntimeException (e);}} /** * Java object->xml. */public string toXml (Object root, string encoding) {try {StringWriter writer = new Stringwrite R (); Createmarshaller (encoding). Marshal (Root, writer); return writer.tostring ();} catch (Jaxbexception e) {throwNew RuntimeException (e);}} /** * Java Object->xml, specifically supports the case of root element is collection. */@SuppressWarnings ("unchecked") public String toXml (Collection root, String rootname, string encoding) {try { Collectionwrapper wrapper = new Collectionwrapper (); wrapper.collection = root; jaxbelement<collectionwrapper> wrapperelement = new jaxbelement<collectionwrapper> (new QName (RootName), Collectionwrapper.class, wrapper); StringWriter writer = new StringWriter (); Createmarshaller (encoding). Marshal (Wrapperelement, writer); return Writer.tostring ();} catch (Jaxbexception e) {throw new RuntimeException (e);}} /** * Xml->java Object. */@SuppressWarnings ("unchecked") public <T> T fromxml (String xml) {try {StringReader reader = new StringReader (XML) ; return (T) Createunmarshaller (). Unmarshal (reader);} catch (Jaxbexception e) {throw new RuntimeException (e);}} /** * Xml->java Object, which supports case sensitivity or insensitivity. */@SuppressWarnings ("unchecked") public <T> T FromXml (String XML, Boolean casesensitive) {Try {String fromxml = xml;if (!casesensitive) FromXml = Xml.tolowercase (); StringReader reader = new StringReader (fromxml); return (T) Createunmarshaller (). Unmarshal (reader); catch (Jaxbexception e) {throw new RuntimeException (e);}} /** * Create Marshaller, set encoding (can be null). */public Marshaller Createmarshaller (String encoding) {try {Marshaller Marshaller = Jaxbcontext.createmarshaller (); Marshaller.setproperty (Marshaller.jaxb_formatted_output, boolean.true); if (Stringutils.isnotblank (encoding)) { Marshaller.setproperty (marshaller.jaxb_encoding, ENCODING);} return marshaller;} catch (Jaxbexception e) {throw new RuntimeException (e);}} /** * Create Unmarshaller. */public Unmarshaller Createunmarshaller () {try {return jaxbcontext.createunmarshaller ();} catch (Jaxbexception e) { throw new RuntimeException (e);}} /** * Package Root Element is the case of collection. */public Static class Collectionwrapper {@SuppressWarnings ("unchecked") @XmlAnyElementprotected Collection Collection ;}}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Using JAXB to convert instances of Java objects and XML strings to each other

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.