How to convert XML to java value object?

What open source libraries are available for converting XML to a java value object?

There is a way in .Net to do this easily with XML serialization and attributes. I would suggest that there is some parallel in java. I know how to do this with a DOM or SAX parser, but I was wondering if there is an easier way.

I have a predefined XML format that looks something like this.

<FOOBAR_DATA> <ID>12345</ID> <MESSAGE>Hello World!</MESSAGE> <DATE>22/04/2009</DATE> <NAME>Fred</NAME> </FOOBAR_DATA> 

In .Net, I can do something like this to bind my object to data.

 using System; using System.Xml.Serialization; namespace FooBarData.Serialization { [XmlRoot("FOOBAR_DATA")] public class FooBarData { private int _ID = 0; [XmlElement("ID")] public int ID { get { return this._ID; } set { this._ID = value; } } private string _Message = ""; [XmlElement("MESSAGE")] public string Message { get { return this._Message; } set { this._Message = value; } } private string _Name = ""; [XmlElement("NAME")] public string Name { get { return this._Name; } set { this._Name = value; } } private Date _Date; [XmlElement("DATE")] public Date Date { get { return this._Date; } set { this._Date= value; } } public FooBarData() { } } } 

I was wondering if there is a method using annotations similar to .Net or possibly Hibernate, which will allow me to bind my value object to predefined XML.

+2
source share
4 answers

I like XStream alot, especially compared to JAXB - unlike JAXB, XStream you don't need XSD. This is great if you have several classes that you want to serialize and deserialize in XML, without the heavy need to create XSD, run jaxc to create classes from this schema, etc. XStream, on the other hand, is pretty lightweight.

(Of course, there are many times when JAXB is suitable, for example, when you have an existing XSD that is suitable for this occasion ...)

+13
source

JAXB allows you to convert an XML Schema (XSD) file to a collection of Java classes. This may be more "structured" than the XMLEncoder / Serializable approach, which provides Andy's answer (excellent, by the way).

+2
source

Java has an XMLEncoder that can be used to serialize an object into XML. The only requirement is that your object implements "Serializable".

Here is an example:

http://www.developer.com/java/web/article.php/1377961

+1
source

JiBX is another option.

For more information on binding data to Java-XML, see Serializing XML in Java?

+1
source

All Articles