简体   繁体   中英

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?

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()))

You can also use this simple workaround:

@Path("translation")
@ElementMap(inline=true)
Map translation;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM