views:

2230

answers:

4

What kind of open-source libraries are available to convert XML into a java value object?

In .Net, there is a way to easily do this with xml serialization and attributes. I would imagine there some parallel in java. I know how to do this with a DOM or SAX parser, but I was wondering if there was 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 the 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 was a method using annotations, similar to .Net or perhaps Hibernate, that will allow me to bind my value object to the predefined-XML.

+1  A: 

Java has an XMLEncoder that you might be able to use to serialize an object to XML. The only requirement is that your object implements "Serializable."

Here's an example:

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

Andy White
A: 

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

Chris Jester-Young
+4  A: 

I like XStream alot, especially compared to JAXB - unlike JAXB, XStream doesn't need you to have an XSD. It's great if you have a handful of classes you want to serialize and deserialize to XML, without the heavy-handed-ness of needing to create a XSD, run jaxc to generate classes from that schema, etc. XStream on the other hand is pretty lightweight.

(Of course, there are plenty of times where JAXB is appropriate, such as when you have a pre-existing XSD that fits the occasion...)

matt b
Very easy to use. I had heard of this before, but I had not put it into use. Thanks!
Kevin
A: 

JiBX is another option.

For more opinions on Java-to-XML data binding, see XML serialization in Java?

Cheeso