Search code examples
javaxmlxml-serialization

How to stop Simple from writing `class` attributes to XML files?


I'm using Simple to read and write 3rd party XML files. Reading works great, but when writing collections the library puts extra class attributes in the resulting file, like this:

<translation class="java.util.Collections$UnmodifiableMap">
    <!-- stuff here-->
</translation>

My schema doesn't allow for these, I'd like to have plain tags with just the attributes I explicitly put there, like these:

<translation>
    <!-- stuff here-->
</translation>

How can I tell Simple to stop writing these and just guess what collection it should use, like it usually does?


Solution

  • The solution is actually mentioned on project's page, you have to use a Visitor. It's quite simple:

    public class ClassAttributeRemoverVisitor implements Visitor {
        @Override
        public void read(Type type, NodeMap<InputNode> node) throws Exception {
            // Do nothing, framework will guess appropriate class on its own
        }
    
        @Override
        public void write(Type type, NodeMap<OutputNode> node) throws Exception {
            OutputNode element = node.getNode();
            element.getAttributes().remove("class");
        }
    }
    

    To use this visitor, you have to add a VisitorStrategy to Persister's constructor:

    new Persister(new VisitorStrategy(new ClassAttributeRemoverVisitor()))