Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using SimpleXML, how to ignore xml elements I don't have in my object class when deserializing

I'm using SimpleXml on Android to deserialize an xml which I have no control over. Now, every time the xml changes, it brakes my app because I don't have the new element defined in my object class. Is there a way I could specify SimpleXML just to ignore those missmaps? Looked at the documentation and can't find anything to help me solve it.

like image 460
Alex Avatar asked Apr 21 '12 22:04

Alex


2 Answers

I'm pretty sure you can get around the strict mapping by replacing your regular @Root declaration with @Root(strict=false), which will eliminate the requirement that every element should match a field in your class definition. More precisely, from the documentation:

This is used to determine whether the object represented should be parsed in a strict manner. Strict parsing requires that each element and attribute in the XML document match a field in the class schema. If an element or attribute does not match a field then the parsing fails with an exception. Setting strict parsing to false allows details within the source XML document to be skipped during deserialization.

There's also an example given in the list of tutorials on the Simple XML project site.

like image 177
MH. Avatar answered Nov 06 '22 06:11

MH.


You can specify strict mode to be disabled for all tags for a particular read by adding in "false" as the last parameter. Also from their documentation:

Should there be more than a single object that requires loose mapping then using the Root annotation might not be the ideal solution. In such a scenario the persister itself can be asked to perform loose mapping. Simply pass a boolean to the read method indicating the type of mapping required. By default the persister uses strict mapping, which can be overridden on an object by object basis using the Root annotation, as shown in the above example. However, this default can be overridden as can be seen in the code snippet below.

Contact contact = serializer.read(Contact.class, source, false);
like image 23
amitavk Avatar answered Nov 06 '22 07:11

amitavk