We have an XML that needs to be converted to an object and vice versa. Something like Xstream does. Until now we were using Xstream to marshall and unmarshall the object/xml. However the problem is that an object that corresponds to XML in xstream, needs to have all the tags as attributes; else if XML contains any extra tags which are not present in object; it bombs.
Or, we need to have custom convertors written to make sure that the operation goes as开发者_开发知识库 desired. I was also suggested that common digester allows Xpath parsing from XML to an object.
I am wondering what is the best approach; as long as:
- I just want to convert XML to Object and vice versa.
- Have the ability to silently ignore any fields in XML that map not be present in mapping object.
What do you suggest?
You need to use a custom MapperWrapper as documented here http://pvoss.wordpress.com/2009/01/08/xstream/
XStream xstream = new XStream() {
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
@Override
public boolean shouldSerializeMember(Class definedIn,
String fieldName) {
if (definedIn == Object.class) {
return false;
}
return super.shouldSerializeMember(definedIn, fieldName);
}
};
}
};
The only thing it does is tell XStream to ignore all fields that it does not know to deal with.
You might want to take a look at this question...
What is the best way to convert a java object to xml with open source apis
These are some of the libraries that it lists...
- http://simple.sourceforge.net/
- http://x-stream.github.io/
- http://xmlbeans.apache.org/
- http://www.rgagnon.com/javadetails/java-0470.html
I would suggest using http://simple.sourceforge.net/ I uses annotations to map attributes and elements and has a "non strict" mode which enables you to read from the XML document ignoring all attributes and elements not present in the Java object.
精彩评论