Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert a java object to xml with open source apis [closed]

I was wondering what the best or most widely used apis are to convert a java object to xml. I'm fairly new on the subject. Is there some sort of api call you can make to pass in an object and return xml? Or is it much more tedious where as you need to construct the document manually by pulling out object values?

I have been reading about xerces, sax, and jaxb. I would like to continue along this open source route.

Thanks!

like image 440
Atma Avatar asked Apr 10 '09 00:04

Atma


People also ask

Can we convert string to XML in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.


1 Answers

JAXB is definitely the solution.

Why? Well, it's inside the JDK 6, so you'll never find it unmaintained.

It uses Java annotations to declare XML-related properties for classes, methods and fields.

Tutorial 1

Tutorial 2

Note: JAXB also enables you to easily 'unmarshal' XML data (which was previously marshalled from Java object instances) back to object instances.

One more great thing about JAXB is: It is supported by other Java-related technologies, such as JAX-RS (a Java RESTful API, which is availible as part of Java EE 6). JAX-RS can serve and receive JAXB objects on the fly, without the need of marshalling/unmarshalling them. You might want to check out Netbeans, which contains out-of-the-box support for JAX-RS. Read this tutorial for getting started.

edit:

To marshall/unmarshall 'random' (or foreign) Java objects, JAXB offers fairly simple possibility: One can declare an XmlAdapter and 'wrap' existing Java classes to be JAXB-compatible. Usage of such XmlAdapter is done by using the @XmlJavaTypeAdapter-annotation.

like image 187
ivan_ivanovich_ivanoff Avatar answered Oct 13 '22 08:10

ivan_ivanovich_ivanoff