java - 简单-XML : Overriding an element name at runtime

标签 java xml simple-framework

我正在使用 simple-xml 在我的 Java 应用程序中执行 XML 序列化/反序列化。我有一个类如下:

@Root(name="config")
public class Config{
    @Element(name="update_interval")
    private int updateInterval;

    @Element(name="timestamp")
    private long timestamp;

    //...
    //...
}

现在,这将生成如下 XML:

<config>
    <update_interval>2000</update_interval>
    <timestamp>1234567890</timestamp>
</config>

问题:

如何在运行时覆盖元素名称,以便在某些情况下 XML 读取如下?

<config>
    <updt_int>2000</updt_int>
    <ts>1234567890</ts>
</config>

编辑:

为了澄清,我只想在某些情况中覆盖元素名称。所以基本上,

if(condition){
    //Override Element Names
} else {
    //Serialize Normally
}

最佳答案

在这种情况下,我找到了一种实现序列化的简单方法,这要归功于 this comment .

但是,我无法反序列化这样的 XML 文档。这是我的部分解决方案:

/*
 * Config.java
 */

@Root(name="config", strict = false)
public class Config {

    @Element(name="timestamp", required = false)
    private long timestamp;

    @Element(name = "update_interval", required = false)
    private int updateInterval;

    public Config() {
    }

    public int getUpdateInterval() {
        return updateInterval;
    }

    public void setUpdateInterval(int updateInterval) {
        this.updateInterval = updateInterval;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    @Override
    public String toString() {
        return "Config{" +
                "timestamp=" + timestamp +
                ", updateInterval=" + updateInterval +
                '}';
    }
}



/*
 * Custom Visitor implementation
 */
public class MyInterceptor implements Visitor {

    private static int sReadCount = 0;
    private static int sWriteCount = 0;
    @Override
    public void read(Type field, NodeMap<InputNode> node) throws Exception {
        /*
         * This is where I need help!
         *
         * 
         * This method is only called once: for the <config> node
         * It is not called for the other nodes since they are not "recognized" 
         * i.e., there are no annotations for the nodes <ts> and <updt_int>
         */

        System.out.println("Read Count : "+ (++sReadCount));
        System.out.println(node.getName());
        System.out.println(node.getNode());

    }

    @Override
    public void write(Type field, NodeMap<OutputNode> node) throws Exception {

        /* 
         * This works like a charm.
         */
        System.out.println("Write Count : "+ (++sWriteCount));
        OutputNode opNode = node.getNode();
        if("timestamp".equals(opNode.getName())){
            opNode.setName("ts");
        }
        if("update_interval".equals(opNode.getName())){
            opNode.setName("updt_int");
        }

    }

}

/*
 *
 */ Main class
public class Bootstrap {

    static final Random RANDOM = new Random();
    public static void main(String [] args){
        Config cfg = new Config();
        cfg.setTimestamp(RANDOM.nextLong());
        cfg.setUpdateInterval(1000);

        Serializer serializer = new Persister(new VisitorStrategy(new MyInterceptor()));

        StringWriter writer = new StringWriter();
        try {
            serializer.write(cfg, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String serialized = writer.toString();
        System.out.println(serialized);

        Config desCfg = null;
        try {
            desCfg = serializer.read(Config.class, serialized);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(desCfg != null){
            System.out.println(desCfg.toString());
        }
    }
}

关于java - 简单-XML : Overriding an element name at runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12724517/

相关文章:

java - 了解简单 XML 解析器 - 新文件输出 - Java

java - 使用简单 XML 序列化 Treemap<String, String>

java - 在 strings.xml 中定位和删除未引用的值

android - 如何使用 XML 在 android 编程中创建一个 tabhost 并重命名每个选项卡?

xml - 基于属性满足条件的节点数

javascript - 如何从js向xml文件添加内容

java - 我怎样才能找到两个时间之间的差异?

java - 通过 Java8 函数获取结果的最佳方式是什么?

java - 如何使用 HttpClient 进行 WebDav 调用?

Android - 简单的 XML 框架。 @Convert 干扰@Attribute - 如何解决这个问题?