我想将一个复杂的XML元素列表解析到一个Map中,其中的键是属性,值是整个对象/元素。

这是我的XML的示例:

<product>
    <documents>
        <document code="100" clazz="DocumentA">
            <properties>
                <property name="PropA" value="123" />
                <property name="PropB" value="qwerty" />
                <property name="PropC" value="ABC" />
            </properties>
        </document>
    </documents>
</product>


我的班级Document的示例:

public class Document {
    private Integer code;
    private String clazz;
    private List<Propertiy> properties;

    //getters and setters...
}


我不知道是否可能,但是我想将文档元素解析为Map,关键是属性代码。

有人能帮我吗?

最佳答案

您可以尝试使用适配器。让我们根据您的xml开始构建POJO。首先您有产品:

@XmlRootElement
public class Product {

    @XmlElementWrapper(name = "documents")
    @XmlElement(name = "document")
    private List<Document> documents;
}


然后在该产品中记录:

@XmlRootElement
public class Document {

    @XmlAttribute
    private Integer code;
    @XmlAttribute
    private String clazz;
    @XmlElement(name = "properties")
    private Properties properties;

}


在属性内,我们使用适配器以获取所需的Map:

@XmlAccessorType(XmlAccessType.FIELD)
public class Properties {

    @XmlElement(name = "property")
    @XmlJavaTypeAdapter(MyMapAdapter.class)
    private Map<String, String> properties;
}


我们的适配器将以一种能够理解传入XML的方式来处理传入xml,并将其改编为其他形式(即map)。因此,首先像xml中那样为该属性创建一个POJO:

@XmlAccessorType(XmlAccessType.FIELD)
public class Property {

    @XmlAttribute
    private String name;
    @XmlAttribute
    private String value;

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }
}


然后我们在适配器中使用它:

public class MyMapAdapter extends XmlAdapter<Property, Map<String, String>> {

    private HashMap<String, String> hashMap = new HashMap<String, String>();

    @Override
    public Map<String, String> unmarshal(Property v) throws Exception {
        hashMap.put(v.getName(), v.getValue());
        return hashMap;
    }

    @Override
    public Property marshal(Map<String, String> v) throws Exception {
        // do here actions for marshalling if u also marshal
        return null;
    }
}


运行此命令将取消对有效负载进行封送,并且将按需要在映射中具有值。希望能帮助到你

10-07 13:17
查看更多