Using JAXB in Java EE to implement the conversion of the __java and XML documents to each other

Source: Internet
Author: User

JAXB (Java architecture for XML Binding) is an industry standard and is a technology that can generate Java classes from XML schemas.

You can allow Java objects and XML documents to be converted to each other.

Let's say there's a pojo.

Package com.xyz;

Import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Boy
{
String name = "John";

Public String GetName ()
{
return name;
}

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

The annotation @xmlrootelement above class indicates that boy this class is the root element of the XML document

Then write a unit test class test

Package org.test;

Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import Java.io.StringReader;

Import Javax.xml.bind.JAXBContext;
Import javax.xml.bind.JAXBException;
Import Javax.xml.bind.Marshaller;
Import Javax.xml.bind.Unmarshaller;
Import Javax.xml.transform.stream.StreamSource;

Import Org.junit.Test;

Import Com.xyz.Boy;

public class Jaxbtest
{
@Test
public void Jaxbtest () throws Jaxbexception, FileNotFoundException
{
Jaxbcontext context = jaxbcontext.newinstance (Boy.class);

Marshaller Marshaller = Context.createmarshaller ();

Boy Boy = new Boy ();

Marshaller.marshal (boy,new fileoutputstream ("Welcome.xml"));


System.out.println ("==================================");

Unmarshaller Unmarshaller = Context.createunmarshaller ();

Boy boy2 = (Boy) unmarshaller.unmarshal (new Streamsource) (New File ("Welcome.xml"));

System.out.println (Boy2.getname ());

}
}
Note that the Marshaller Unmarshaller is two core classes. XML documents and Java objects can be converted to each other.


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.