【问题标题】:parsing HashMap into xml with Simple XML - JAVA使用简单 XML 将 HashMap 解析为 xml - JAVA
【发布时间】:2020-11-23 18:10:11
【问题描述】:

我需要将值放在一个 pat 中,作为我的 XML 文件的值:

Map<String, String> props = new HashMap<>();
props.put("role", "Admin");
props.put("externalId", "2ew1Q");
props.put("Property", "internal");
props.put("Execution", "internal");

我的预期输出应该是:

<role>Admin</role>
<externalId>2ew1Q</externalId>
<Property>internal</Property>
<Execution>internal</Execution>

但我得到的不是它,而是

<entry string="role">Admin</entry>
<entry string="Execution">internal</entry>
<entry string="externalId">2ew1Q</entry>
<entry string="Property">internal</entry>

我必须使用简单 XML 来完成,这是我的代码:

    @Root
    public class Data {
    
        @ElementMap(entry = "property", key = "key", attribute = true, inline = true)
        private Map<String, String> customProps;
    
        public Map<String, String> getData() {
            return customProps;
        }
    
        public void setData(Map<String, String> data) {
            this.customProps = data;
        }
    }


public static void main(String[] args) throws Exception {

        Map<String, String> props = new HashMap<>();

        props.put("role", "Admin");
        props.put("externalId", "2ew1Q");
        props.put("Property", "internal");
        props.put("Execution", "internal");


        Data customProps = new Data();
        customProps.setData(props);

        Serializer serializer = new Persister();
        File result = new File("example.xml");
        serializer.write(customProps, result);
}

【问题讨论】:

    标签: java xml parsing hashmap simple-framework


    【解决方案1】:

    尝试: @ElementMap(entry = "property", key = "key", attribute = false, inline = true)

    【讨论】:

    • 不行,我已经试过了,但是不行,attribute = false 将条目转换为父标签。就像这样: roleAdminExecutioninternal .....
    • 你能不能只做:private String role; private String externalId; 等,然后将这些变量设置为你想要的。然后它们会自动变成节点
    • 问题是这些值来自数据库,所以并不总是“角色”,它可能来自“transferId”甚至“asd”(开玩笑),所以想法是不管是数据库中的值,映射可以采用该值并映射到 XML 中。
    猜你喜欢
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多