I currently use a piece of XML like the following
Frank Smith
100023412
1
Since XStream 1.4.5 durring marshaller declaration it's enough to use ignoreEnknownElements() method:
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.getXStream().ignoreUnknownElements();
...
to ignore unnecessary elements.
First of all, thanks for sharing this answer. It was very useful. However, the code mentioned above has issues. It does not have @Override annotations, which are a must to use this piece of code. Here is the updated code that works:
XStream xstream = new XStream(new StaxDriver()) {
@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);
}
};
}
};
From the x-stream FAQ:
How does XStream deal with newer versions of classes?
- If a new field is added to the class, deserializing an old version will leave the field uninitialized.
- If a field is removed from the class, deserializing an old version that contains the field will cause an exception. Leaving the field in place but declaring it as transient will avoid the exception, but XStream will not try to deserialize it.
- ...
- implement a custom mapper to ignore unknown fields automatically (see acceptance test CustomMapperTest.testCanBeUsedToOmitUnexpectedElements())
XStream 1.4.5 supports dealing with tags which are not implemented. Use ignoreUnknownElements for tags which are not implemented yet or has been removed and you are dealing with old xml. You can also specify which particular tag you would like to ignore.
As it took me more than 15 minutes to find this answer, I thought I would post it.
XStream xstream = new XStream(new DomDriver()) {
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
public boolean shouldSerializeMember(Class definedIn, String fieldName) {
try {
return definedIn != Object.class || realClass(fieldName) != null;
} catch(CannotResolveClassException cnrce) {
return false;
}
}
};
}
};
This seems to skip xml items that are not in your objects.
I asked for exactly the same problem.
How can I make a XStreamMarshaller skip unknown binding?
And I got a comment linking this post.
I solved the my problem by extending the XStreamMarshaller
.
public class ExtendedXStreamMarshaller extends XStreamMarshaller {
@Override
protected void configureXStream(final XStream xstream) {
super.configureXStream(xstream);
xstream.ignoreUnknownElements(); // will it blend?
}
}