JAXB implements Java objects and XML transformations (one)

Source: Internet
Author: User

Enables transformations between Java object Objects and XML using Marshaller and Unmarshaller

First, create a simple boy object

@XmlRootElement (name= "Root")
@XmlAccessorType (xmlaccesstype.property) public
class Boy {
	
	private String name = "AA";

	Public String GetName () {return
		name;
	}

	public void SetName (String name) {
		this.name = name;
	}
	
}

where @xmlrootelement (name= "root") indicates the root element of the XML (name= "root") this is the same element that redefined the XML file, and if there is no such name definition, the XML root element defaults to the object name

The object is then converted to XML through the Marshaller class implementation, and the Unmarshaller class is used to convert between XML and classes

public class Jaxbtest {public

	static void Main (string[] args) throws Jaxbexception {
		Jaxbcontext context = Jaxbco Ntext.newinstance (boy.class);
		
		Marshaller Marshaller = Context.createmarshaller ();
		Unmarshaller Unmarshaller = Context.createunmarshaller ();
		
		System.out.println ("----------marshaller--------------");
		Boy Boy = new Boy ();
		Marshaller.marshal (Boy, System.out);
		
		System.out.println ("\ n----------unmarshaller--------------");
		convert XML to corresponding Java object
		String xml = "<Root><name>aa</name></Root>";//the label name must be consistent with the properties of the boy object
		Boy B = (Boy) Unmarshaller.unmarshal (new StringReader (XML));
		System.out.println (B.getname ());
	}
	
Finally convert print results

----------Marshaller--------------
<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"?><root><name>aa</name></root>
----------Unmarshaller--------------
Aa

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.