[英]How to convert different child XML elements from an XML node into a generic java type instances using XStream?
從下面的簡單XML中,我想創建一個SomeApplication實例,其中包含Field實例的集合,其中每個Field實例代表<some-application>的子元素。 Field實例將具有兩個字符串屬性,即名稱和值,分別從節點名稱和節點值分配。
XML輸入:
<some-application>
<field1>foo</field1>
<field2>bar</field2>
</some-application>
Java類型:
public class Field {
private String name;
private String value;
public Field(String name, String value) {
this.name = name;
this.value = value;
}
public String getName(){
return name;
}
public String getValue(){
return value;
}
}
public class SomeApplication {
private List<Field> fields;
public SomeApplication(){
fields = new ArrayList<Field>();
}
public void addField(Field field){
fields.add(field);
}
}
將字段元素(<some-application>的子元素)轉換為Field實例的最佳策略是什么?
請注意,為了簡潔起見,我簡化了要求。
提前致謝。
我已經設法使用自定義轉換器SomeAppConverter實現了這一目標 。 在我的自定義轉換器中,在解組時,對於遇到的每個子節點,我都使用節點名稱和值創建Field類型的實例。 以下是我的自定義轉換器
public class SomeApplicationConverter implements Converter {
@Override
@SuppressWarnings("unchecked")
public boolean canConvert(Class type) {
if (type.equals(SomeApplication.class)) {
return true;
}
return false;
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
throw new UnsupportedOperationException(
"Marshalling is not supported yet");
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
SomeApplication application = new SomeApplication();
while (reader.hasMoreChildren()) {
reader.moveDown();
String name = reader.getNodeName();
String value = reader.getValue();
Field field = new Field(name, value);
application.addField(field);
reader.moveUp();
}
return application;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.