[英]How to parse a complex element into a Map, using a attribute as key and the whole element as value, in JAXB Adapter
我想將一個復雜的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;
}
}
運行此命令將取消對有效負載進行封送,並且將按需要在映射中具有值。 希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.