I'm trying to figure out the simplest way to map an xml file to to a plain old java object.
Note: That in my example the xml doesn't quite match up with my intended POJO.
///////// THE XML
<?xml version="1.0" encoding="UTF-8"?>
<Animal>
<standardName>
<Name>Cat</Name>
</standardName>
<standardVersion>
<VersionIdentifier>V02.00</VersionIdentifier>
</standardVersion>
</Animal>
////// THE INTENDED POJO
class Animal
{
private String name;
private String versionIdentifier;
}
Regular JAXB (with annotations) won't work as the JAXM Element name annotations don't allow me to specifiy nested elements. (i.e. standardName/Name).
I've looked at Jibx but it seems overly complicated, and no full examples are provided for what I want to do.
Castro seems like it would be able to do what I want (using mapping files), but I wonder if there are any other possible solutions. (Possibly that would allow me to skip mapping files, and just allow me to specify everything in annotations).
Thanks
EclipseLink JAXB (MOXy) allows you to do the path based mapping that you are looking for:
#XmlRootElement
class Animal
{
#XmlPath("standardName/Name/text()")
private String name;
#XmlPath("standardVersion/VersionIdentifier/text()");
private String versionIdentifier;
}
For more information see:
http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/MOXyExtensions
EclipseLink also allows the metadata to be specified using an external configuration file:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/ExternalizedMetadata
This article may help you... it only requires you to know xpath
http://onjava.com/onjava/2007/09/07/schema-less-java-xml-data-binding-with-vtd-xml.html
Jakarta Commons Digester should do what you want.
Alternatively, I would recommend writing a transformation class that uses XPath to retrieve elements from the XML.
I consider JiBX the best of the bunch (JAXB, Castor, XMLBeans, etc.), particularly because I favor mapping files over annotations. Admittedly it has a decent learning curve, but the website has a lot of good examples. You must have missed the tutorial.
If you are only going one way (XML --> POJO) you could use Digester.
Side comment: I prefer mapping files over annotations because annotations:
clutter the code (especially when using annotations from several products)
mix concerns (XML, database, etc. in domain layer)
can only bind to a single XML (or database, or web service, etc.) representation
Related
Suppose i have a BOOK.java file with the fields(id, name, author) and now while marshalling it to XML file, I want only id to be written in XML file but that has to be decided by some condition. So I was thinking to inject #XmlTransient annotations to other two fields on that condition at runtime. Is it possible to inject an JAXB annotations at runtime? Can i do that and if i can, how can i do so?
Is there any way other then using javassist to do so ?
It sounds like you just want something that's not JAXB. JAXB is great when it fits, but it's pretty restrictive in what it allows you to do. Something like XStream would probably fit your needs better. You can write a custom Converter that will handle all the logic of whether to write a particular field or not.
Basically, I want to have an interface for converting Objects to/from their XML or JSON String representation, something like
public interface IStringifier{
/**
Converts the Object to it's String representation, e.g. XML or JSON
*/
public String toString(Object o);
/**
Converts from the String representation (e.g. XML or JSON) to an Object
*/
public Object fromString(String s, Class<?> clazz);
}
Such an interface would be fairly simple to implement in GSON, XStream etc. but by abstracting it you are abstracted from knowing just what is going on underneath. And you are decoupled from one of the many many XML or JSON libraries, so clients are freer to pick their favorite.
Is there any "standard" Java interface for this? Something in Guava, Apache, etc?
(added) None of the answers were what I really wanted ("yes, in javax.obscure.interfaces there's what you want") but thanks for the replies. I'll accept Tom's answer as the most informative/provocative. And maybe I'll clean up the code I have and try to create a standard. :-)
JAXB (JSR-222) is the Java SE/EE standard for converting objects to/from XML. It can be used standalone and is the standard binding layer for JAX-WS (SOAP) and JAX-RS (RESTful) Web Services. Below is a link to an example of specifying an alternate provider via a jaxb.properties file.
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
There currently isn't a standard API for JSON binding.
I think you're overthinking this. You don't actually care about turning objects into Strings, you want to be able to serialize objects to different formats without knowing what that format is. But who says that different format is a String? What happens when you want your object to be available as a protocol buffer? That's a binary format, not a character format -- so stringify() won't help there. Ultimately, it's up to you to architect your application to be as independent as possible of those details.
XML and JSON are unrelated, so this is actually two questions:
For JSON, although "unofficial", a popular library is GSON.
For XML, see Blaise's answer
One popular JSON-to-Java binding library is Jackson
One popular XML-to-Java binding library is XStream
If you intend to use this in a web application, maybe you would like to consider Spring 3 MVC's facilities for this. Through annotations it does the conversion automatically and you can tell it whether you want XML or JSON (or various other formats). This might be the common interface you are looking for too.
I call an XML document three-layered if its structure is laid out as following: the root element contains some container elements (I'll call them entities), each of them has some simpleType elements inside (I'll call them properties).
Something like that:
<data>
<spaceship>
<number>1024</number>
<name>KTHX</name>
</spaceship>
<spaceship>
<number>1624</number>
<name>LEXX</name>
</spaceship>
<knife>
<length>10</length>
</knife>
</data>
where spaceship is an entity, and number is a property.
My problem is stated below:
Given
schema: an arbitrary xsd file describing a three-layered document, loaded at runtime.
xmlDocument: an xml document conforming to the schema.
Create
A Map<String, Map <String, Object>> containing data from the xmlDocument, where first key corresponds to entity, second key correponds to this entity's property, and the value corresponds to this property's value, after casting it to a proper java type (for example, if the schema sets the property value to be xs:int, then it should be cast to Integer).
What is the easiest way to achieve this result with existing libraries?
P. S.
JAXB is not really an option here. The schema might be arbitrary and unknown at compile-time. Also I wish to avoid an excessive use of reflection (associated with converting the beans to maps). I'm looking for something that would allow me to make the typecasts while xml is being parsed.
I think XMLBeans is worth a shot; saved the day more than once...
Basically you run an ant script to generate the beans handling the schema, then you iterate over the nodes to build your map.
I think JAXB (tutorial here) is the easiest way to do this.
Create your XML structure like:
#XmlRootElement
class data {
public List<SpaceShipType> spaceship;
public KnifeType knife;
}
class SpaceShipType {
public int number;
public String name;
}
class KnifeType {
public int length;
}
Then create the object tree, and use JAXB.marshall() to write the XML.
If you have an existing XSD, use the xjc tool to create the classes for you.
You will need reflections if the schema is unknown at compile time.
I suggest to take a look at some other tools like xstream.
I could recommend the simple framework or you could do parsing/wrinting xml with pure dom4j as I did in the timefinder project. I used the 'pure' approach because I had cycles in my object graph, but I wanted that the xml could be validated with an xml schema (and I did not want to use JAXB)
I have finally went with using Castor library for parsing the schema and assigning data types manually.
JAXB works well until I need to do something like serialize beans for which I cannot modify the source. If the bean doesn't have a default constructor or if it refers to objects I want to mark transient then I'm stuck writing a separate bean which I can annotate and then manually copy the information over from the other bean.
For instance, I wanted to serialize exception objects, but found that the only way to do that was use a hack that required using com.sun.* classes.
So, what alternatives are there? What's the next most popular xml serializing api? It would be nice to be able to do things like:
Choose at serialization time whether to include certain fields in the result. (marking things transient when running the serializer).
Handle loops in the object graph by using references or something other than just dying.
Perhaps annotate an object so that in version 1 it serializes things in one way and in version 2 it serializes them in another. Then when serializing I just choose which version of the object ot serialize.
Have a way to generate XSDs from annotations on an object.
Basically I just want more flexibility than I currently have with JAXB.
Well the standard answer for wanting a uber configurable serialisation framework is xstream.
JAXB is a spec, so you can pick from different implementations. EclipseLink JAXB (MOXy) has extensions for what you are asking:
Externalized Metadata
Useful when dealing with classes for which you cannot annotate the source or to apply multiple mappings to an object model.
http://bdoughan.blogspot.com/2010/12/extending-jaxb-representing-annotations.html
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/EclipseLink-OXM.XML
XPath Based Mapping
For true meet-in-the-middle OXM mapping:
http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
http://bdoughan.blogspot.com/2011/03/map-to-element-based-on-attribute-value.html
http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/MOXyExtensions
JPA Compatibility
Including support for bi-directional relationships.
http://bdoughan.blogspot.com/2010/07/jpa-entities-to-xml-bidirectional.html
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA
Also look at JIBX. It's a good xml<->object mapper. My experience is though that if your objects have a somewhat funky relationships it's often easier to create a wrapper object that hides that complexity and then map that object with JIBX.
XStream is a popular XML serialisation library that claims to be able to serialize just about anyting, regardless of constructors or other problems (even deserialize final fields). Give it a try.
Requires no modifications to objects. Serializes internal fields, including private and final. Supports non-public and inner classes. Classes are not required to have default constructor.
If you have a Java object and an XML schema (XSD), what is the best way to take that object and convert it into an xml file in line with the schema. The object and the schema do not know about each other (in that the java classes weren't created from the schema).
For example, in the class, there may be an integer field 'totalCountValue' which would correspond to an element called 'countTotal' in the xsd file. Is there a way of creating a mapping that will say "if the object contains an int totalCountValue, create an element called 'countTotal' and put it into the XML".
Similarly, there may be a field in the object that should be ignored, or a list in the object that should correspond to multiple XML elements.
I looked at XStream, but didn't see any (obvious) way of doing it. Are there other XML libraries that can simplify this task?
I believe this can be achieved via JAXB using it's annotations. I've usually found it much easier to generate Objects from JAXB ( as defined in your schema) using XJC than to map an existing Java object to match my schema. YMMV.
I'm doing Object do XML serialization with XStream. What don't you find "obvious" with this serializer? Once you get the hang of it its very simple.
In the example you provided you could have something like this:
...
XStream xstream = new XStream(new DomDriver());
xstream.alias("myclass", MyClass.class);
xstream.aliasField("countTotal", MyClass.class, "totalCountValue");
String xml = xstream.toXML(this);
...
for this sample class:
class MyClass {
private int totalCountValue;
public MyClass() {
}
}
If you find some serializer more simple or "cool" than this please share it with us. I'm also looking for a change...
Check the XStream mini tutorial here
I use a java library called JiBx to do this work. You need to write a mapping file (in XML) to describe how you want the XML Schema elements to map to the java objects. There are a couple of generator tools to help with automating the process. Plus it's really fast.
I tried out most of the libraries suggested in order to see which one is most suited to my needs. I also tried out a library that was not mentioned here, but suggested by a colleague, which was a StAX implementation called Woodstox.
Admittedly my testing was not complete for all of these libraries, but for the purpose mentioned in the question, I found Woodstox to be the best. It is fastest for marshalling (in my testing, beating XStream by around 30~40%). It is also fairly easy to use and control.
The drawback to this approach is that the XML created (since it is defined by me) needs to be run through a validator to ensure that it is correct with the schema.
You can use a library from Apache Commons called Betwixt. It can map a bean to XML and then back again if you need to round trip.
Take a look at JDOM.
I would say JAXB or Castor. I have found Castor to be easier to use and more reliable, but JAXB is the standard