XML for POJO and vice versa

Possible duplicate:
What is the best / easiest way to read in an XML file in a Java application?

How to convert XML to POJO and vice versa? Does axis 2 do this? or does java already have built-in features for this? or any other framework? thanks

+6
source share
5 answers

I really recommend you use JAXB .

JAXB is an annotation framework that maps Java classes to XML and XML Schema (and vice versa). This is extremely useful because instead of interacting with the abstract representation of an XML document, you can work with real Java objects that are closer to the area you are modeling.

If you need to create a RESTful web service with automatic serialization / deserialization of Java objects in XML, through JAXB, I also suggest you read this book:

Oreilly RESTful Java with JAX-RS - (Chapter 6. JAX-RS Content Handlers)

+7
source

If you need an easily accessible infrastructure for this, check out xstream

+6
source
+1
source

a simple version of this is built into java> = 1.4 using the XMLEncoder and XMLDecoder .


quick example

use is pretty simple, line by line

 XMLEncoder xmlEncoder = new XMLEncoder( outputStream ); xmlEncoder.writeObject( myObject ); 

will give you something like

 <?xml version="1.0" encoding="UTF-8"?> <java> <object class="your.class.Name"> <void property="fieldName"> <boolean>true</boolean> </void> etc. etc. etc. </object> </java> 

to read the object you just do

 XMLDecoder xmlDecoder = new XMLDecoder( inputStream ); MyClass thing = (MyClass) xmlDecoder.readObject(); 

here is a random tutorial i found on google:
http://www.avajava.com/tutorials/lessons/how-do-i-write-a-javabean-to-an-xml-file-using-xmlencoder.html

this method is not surprisingly flexible, but it is built-in, configured, and highly predictable. may be a good starting point.

Some additional notes:

here is a document that describes the xml format: http://java.sun.com/products/jfc/tsc/articles/persistence3/

and here is another link I just found that explains how the transition from XMLEncoder to jaxb (built in jdk> = 1.6) for more flexibility: http://en.newinstance.it/2010/08/05 / javabeans-to-xml-with-no-libraries /

+1
source

Source: https://habr.com/ru/post/919103/


All Articles