【问题标题】:How to stop Simple from writing `class` attributes to XML files?如何阻止 Simple 将 `class` 属性写入 XML 文件?
【发布时间】:2017-10-01 16:27:18
【问题描述】:

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

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

我的架构不允许这些,我希望有简单的标签,只包含我明确放在那里的属性,如下所示:

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

我怎样才能告诉 Simple 停止编写这些,只是像往常一样猜测它应该使用什么集合?

【问题讨论】:

    标签: java xml xml-serialization


    【解决方案1】:

    解决方案实际上是mentioned on project's page,你必须使用访客。很简单:

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

    要使用这个访问者,你必须在 Persister 的构造函数中添加一个 VisitorStrategy:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-02
        • 2020-03-27
        • 1970-01-01
        • 2011-04-06
        • 1970-01-01
        相关资源
        最近更新 更多