如何阻止 Simple 将 `class` 属性写入 XML 文件?

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

我正在使用 Simple 读取和写入第 3 方 XML 文件。阅读效果很好,但在编写集合时,库会在生成的文件中添加额外的 class 属性,如下所示:

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

我的模式不允许这些,我希望有纯标签,其中只包含我明确放置在那里的属性,如下所示:

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

我怎样才能让 Simple 停止编写这些内容,而只是猜测它应该使用哪个集合,就像它通常那样?

解决办法其实是mentioned on project's page,你得用Visitor。很简单:

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");
    }
}

要使用此访问者,您必须将 VisitorStrategy 添加到 Persister 的构造函数中:

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

您也可以使用这个简单的解决方法:

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