This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to convert a java object to xml with open source apis
I found existing questions 1 and 2 on the subject, but I wasn't sure if it was up-to-date, and the best fit for what I'm trying to do.
I've had one strong suggestion of XMLBeans, but there isn't too much discussion on it here on SO, and it's not even mentioned on the first link above (not with any upvotes, anyway).
Is JAXB still the best recommendation for this? If so, are there any simple tutorials that walkthrough A->B with object->xml?
Update:
I'm being given Lists of java objects, and need to convert them to xml following a given schema.
I prefer to use JAXB that supports both annotation and XML based mapping.
I'd go with XStream, as your question 2 suggests.
It needs no annotations, just configuration, and can serialize simple objects out of the box.
To make the objects fit a given schema, you'd convert them to objects that closely resemble the schema first and serialize those to XML.
The XStream page also holds the tutorials you request.
Related
I am using java, I want to read strings from an XML tag. EX: < blank type="Something">
I need to be able to assign "Something" to a variable. Any ideas?
There are a lot of ways to do this:
You can use the XML APIs provided with Java (SAX or STAX or DOM).
There are libraries that build on the XML APIs (JDOM, DOM4J, or XOM) which are easier to use than the raw APIs.
There's Java-XML databinding, described in Pratik's answer. Java-XML databinding is sometimes overkill, depending on your requirements, and when there are errors they can be hard to figure out. Sometimes it's worthwhile, though. I think JiBX is particularly interesting.
If you don't know where to start, start with XOM. XOM was created by a JDOM contributor, it was designed to be easy to use.
What you want to achieve is referred to as Unmarshalling an XML. Unmarshalling means extracting data from an XML document and using it to construct a Java object or graph of objects. There are various APIs available to do the same. You should have a look at the following links:
JAXB:
http://www.oracle.com/technetwork/articles/javase/index-140168.html
Castor: http://castor.codehaus.org/
JiBX: http://jibx.sourceforge.net/
I'm trying to convert to list of hibernate objects to XML using JAXB. Are there any special considerations OR any reasons a list of hibernate objects with one to many relationship can't be converted?
1.) It seems like PersistentSet provided by Hibernate is not Serializable and hence, can't be converted by JAXB. I would probably would need to cast it to a "Serializable" set. Is this correct? If yes, how do I achieve it?
Edit 1. I'm going to write Set adapter class, similar to this example link. Will update my findings. http://www.objectpartners.com/2010/01/25/using-jpa-and-jaxb-annotations-in-the-same-object/
As mentioned below, there is no need to convert PersistentSet as it is serializable already.
Edit 2 (and Solution). Ok, I'm able to able to make it work.Thanks to Maven's Schemagen which gave the hint that 'java.sql.TimeStamp' is not compatible with JAXB. I wrote an adaptor which converts TimeStamp to Date.
Thanks everyone for guiding on this.
PersistentBag and PersistenceSet, both are serializable. See http://docs.jboss.org/hibernate/core/3.2/api/org/hibernate/collection/PersistentSet.html and http://docs.jboss.org/hibernate/core/3.2/api/org/hibernate/collection/PersistentBag.html
Why don't you use hibernates xml store? It is much easier.
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/xml.html
I'm able to able to make it work.Thanks to Maven's Schemagen which gave the hint that 'java.sql.TimeStamp' is not compatible with JAXB. I wrote an adaptor which converts TimeStamp to Date.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
There is guy here swearing that JAXB is the greatest thing since sliced bread. I am curious to see what Stack Overflow users think the use case is for JAXB and what makes it a good or a bad solution for that case.
I'm a big fan of JAXB for manipulating XML. Basically, it provides a solution to this problem (I'm assuming familiarity with XML, Java data structures, and XML Schemas):
Working with XML is difficult. One needs a way to take an XML file - which is basically a text file - and convert it into some sort of data structure, which your program can then manipulate.
JAXB will take an XML Schema that you write and create a set of classes that correspond to that schema. The JAXB utilities will create the hierarchy of data structures for manipulating that XML.
JAXB can then be used to read an XML file, and then create instances of the generated classes - laden with the data from your XML. JAXB also does the reverse: takes java classes, and generates the corresponding XML.
I like JAXB because it is easy to use, and comes with Java 1.6 (if you are using 1.5, you can download the JAXB .jars.) The way it creates the class hierarchy is intuitive, and in my experience, does a decent job abstracting away the "XML" so that I can focus on "data".
So to answer your question: I would expect that, for small XML files, JAXB might be overkill. It requires you to create and maintain an XML schema, and to use "standard textbook methods" of utilizing Java classes for data structures. (Main classes, small inner-classes to represent "nodes", and a huge hierarchy of them.) So, JAXB is probably not that great for a simple linear list of "preferences" for an application.
But if you have a rather complex XML schema, and lots of data contained within it, then JAXB is fantastic. In my project, I was converting large amounts of data between binary (which was consumed by a C program) and XML (so that humans could consume and modify that data). The resulting XML Schema was nontrivial (many levels of hierarchy, some fields could be repeated, others could not) so JAXB was helpful in being able to manipulate that.
Here's a reason not to use it: performance suffers. There is a good deal of overhead when marshaling and unmarshaling. You might also want to consider another API for XML-Object binding -- such as JiBX:
http://jibx.sourceforge.net/
I use JAXB at work all the time and I really love it. It's perfect for complex XML schemas that are always changing and especially good for random access of tags in an XML file.
I hate to pimp but I just started a blog and this is literally the first thing I posted about!
Check it out here:
http://arthur.gonigberg.com/2010/04/21/getting-started-with-jaxb/
It's an "ORM for XML". Most often used alongside JAX-WS (and indeed the Sun implementations are developed together) for WS Death Star systems.
With JAXB you can automatically create XML representations of your objects (marshalling) and object representations of the XML (unmarshalling).
As far as the XML Schema is concerned, you have two choices:
Generate Java classes from an XSD
Generate an XSD from your Java classes
There are also some simpler XML serialization libraries like XStream, Digester or XMLBeans that might be alternatives.
JAXB is great if you have to code to some external XML spec defined as an XML schema (xsd).
For example, you have a trading application and you must report the trades to the Uber Lame Trade Reporting App and they've given you ultra.xsd to be getting on with. Use the $JAVA_HOME/bin/xjc compiler to turn the XML into a bunch of Java classes (e.g. UltraTrade).
Then you can just write a simple adapter layer to convert your trade objects to UltraTrades and use the JAXB to marshal the data across to Ultra-Corp. Much easier than messing about converting your trades into their XML format.
Where it all breaks down is when Ultra-Corp haven't actually obeyed their own spec, and the trade price which they have down as a xsd:float should actually be expressed as a double!
Why we need JAXB?
The remote components (written in Java) of web services uses XML as a mean to exchange messages between each other. Why XML? Because XML is considered light weight option to exchange message on Networks with limited resources.
So often we need to convert these XML documents into objects and vice versa. E.g: Simple Java POJO Employee can be used to send Employee data to remote component( also a Java programme).
class Employee{
String name;
String dept;
....
}
This Pojo should be converted (Marshall) in to XML document as follow:
<Employee>
<Name>...</Name>
<Department>...</Department>
</Employee>
And at the remote component, back to Java object from XML document (Un-Marshall).
What is JAXB?
JAXB is a library or a tool to perform this operation of Marshalling and UnMarshalling. It spares you from this headache, as simple as that.
You can also check out JIBX too. It is also a very good xml data binder, which is also specialized in OTA (Open Travel Alliance) and is supported by AXIS2 servers. If you're looking for performance and compatibility, you can check it out :
http://jibx.sourceforge.net/index.html
JAXB provides improved performance via default marshalling optimizations.
JAXB defines a programmer API for reading and writing Java objects to and from XML documents, thus simplifying the reading and writing of XML via Java.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What are the lightweight options one has to persist Java objects ?
I'm looking for the easiest possible solution. I don't want anything fancy featurewise just something simple that works with reasonnably simple objects (some collections, relationships and simple inheritance) and doesn't bring too much apparent complexity (if any) to the existing codebase.
The options I'm aware of include Hibernate and frameworks such as EMF but they sound (and have been experienced to be) too complex and time-consuming. I'd like something out of the box, preferably file oriented than dababase oriented, that I can just put on top of my plain old java objects.
This is a newbie question, thanks in advance for any tutorial-like, context clarifying guidance.
db4o is an object database so there's no schema setup and it adapts well to changes in object structure over time.
If you are looking at something simple you might also want the data in a format you can read (not a binary file or database). If that is the case, you should look at JAXB (Java's XML Binding) that is part of Java 6 and later. There are other technologies that may be able to do this better such as XML Beans but this one is built in.
Take a look at this page from Java's API. It is pretty straight forward to serializing and deserializing Java objects.
http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXBContext.html
Basically you use the following:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
// unmarshal from foo.xml
Unmarshaller u = jc.createUnmarshaller();
FooObject fooObj = (FooObject)u.unmarshal( new File( "foo.xml" ) );
// marshal to System.out
Marshaller m = jc.createMarshaller();
m.marshal( fooObj, System.out );
Just make sure your FooObject has the #XmlRootElement annotation. Java bean properties are automatically interpreted but you can use other annotations to control how the XML looks and model more complex objects.
The ObjectOutputStream and ObjectInputStream can do this. It's built into Java and allows you to serialize/deserialize objects quite easily.
The bad thing about these is that if you change your objects you can't import existing old objects. You'll have to think of a way to stay compatible with existing objects that might already be saved on a user's computer, such as adding a version number to your classes and creating the ability to convert old objects to new ones.
More info here:
http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectOutputStream.html
http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectInputStream.html
EDIT:
You may also consider adding the following attribute to all your classes right off the bat. This may allow you to then add attributes to classes and still be able to load old Object files. In RMI-land this works, but I'm not sure about files. Don't ever remove attributes though.
static final long serialVersionUID = 1L;
Try Simple XML persistence http://simple.sourceforge.net. Its really simple and requires no configuration. Just take your existing POJOs and annotate them, then you can read and write them to a file. Cyclical object graphs are supported as well as all Java collections. It can be used like so.
Serializer serializer = new Persister();
MyObject object = serializer.read(MyObject.class, new File("file.xml));
and writing is just as easy
serializer.write(myInstance, new File("file.xml"));
This is an extremely lightweight approach, no dependancies other than standard Java 1.5. Compared with other object to XML technologies such as JAXB, XStream, Castor, which are dependant on a whole host of other projects Simple XML is very lightweight and memory efficient.
See this similar question Light-weight alternative to hibernate. The most light weight framework I know of is iBatis
You could try XStream which is an open source library. All it does is turn your POJOs into XML which you can then saved to disk. It is very easy to use and requires only a few lines of code to use.
One simple approach is to serialize (as in Serializable) your objects to disk.
http://www.devx.com/Java/Article/9931/1954
The simplest option I know of is using Xstream to make an xml file out of ANY java obect.
I have to say the initial learning curve for Hibernate is relatively shallow. You should be able to get a test system up and running in less than a day. It's only when you want the more advanced features where it starts to get steeper. I would recommend you definitely take a look, I mean what's a day if you end up not choosing it?
Having said that, have you considered just serializing your objects directly to disk if you just want something quick n dirty?
I have used PersistentObject extensively in production code and it serves my needs well.
Does somebody know a Java library which serializes a Java object hierarchy into Java code which generates this object hierarchy? Like Object/XML serialization, only that the output format is not binary/XML but Java code.
Serialised data represents the internal data of objects. There isn't enough information to work out what methods you would need to call on the objects to reproduce the internal state.
There are two obvious approaches:
Encode the serialised data in a literal String and deserialise that.
Use java.beans XML persistence, which should be easy enough to process with your favourite XML->Java source technique.
I am not aware of any libraries that will do this out of the box but you should be able to take one of the many object to XML serialisation libraries and customise the backend code to generate Java. Would probably not be much code.
For example a quick google turned up XStream. I've never used it but is seems to support multiple backends other than XML - e.g. JSON. You can implement your own writer and just write out the Java code needed to recreate the hierarchy.
I'm sure you could do the same with other libraries, in particular if you can hook into a SAX event stream.
See:
HierarchicalStreamWriter
Great question. I was thinking about serializing objects into java code to make testing easier. The use case would be to load some data into a db, then generate the code creating an object and later use this code in test methods to initialize data without the need to access the DB.
It is somehow true that the object state doesn't contain enough info to know how it's been created and transformed, however, for simple java beans there is no reason why this shouldn't be possible.
Do you feel like writing a small library for this purpose? I'll start coding soon!
XStream is a serialization library I used for serialization to XML. It should be possible and rather easy to extend it so that it writes Java code.