有些情况下,xml文件是这样的
<body> <entryList> <field name="forumName">General Discussion</field> <field name="createDate">2013-09-11 12:37:02</field> </entryList> </body>
如果使用xstream,就要添加一个转化器实现Converter接口。先把接口贴出来:
import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; public class FieldConverter implements Converter { @Override public boolean canConvert(@SuppressWarnings("rawtypes") Class type) { if (type == Field.class) { return true; } return false; } @Override public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Field field = (Field)source; //writer.startNode("field"); writer.addAttribute("name", field.getName()); writer.setValue(field.getValue()); //writer.endNode(); } @Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Field field = new Field(); String name = reader.getAttribute("name"); field.setName(name); String value = reader.getValue(); field.setValue(value); return field; } }下面是两个POJO封装类:
import java.util.List; public class Body { List<Field> entryList; public Body() { super(); } public List<Field> getEntryList() { return entryList; } public void setEntryList(List<Field> entryList) { this.entryList = entryList; } }
public class Field { String name; String value; public Field() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; public class TestXml { public static void main(String[] aa) { List<Field> entryList = new ArrayList<Field>(); Field field = new Field(); field.setName("forumName"); field.setValue("General Discussion"); entryList.add(field); Field field2 = new Field(); field2.setName("createDate"); field2.setValue("2013-09-11 12:37:02"); entryList.add(field2); Body body = new Body(); body.setEntryList(entryList); XStream xstream = new XStream(); xstream.registerConverter(new FieldConverter()); xstream.alias("field", Field.class); xstream.alias("body", Body.class); String xml = xstream.toXML(body); System.err.println(xml); Body body2 = (Body)xstream.fromXML(xml); System.out.println(body2); } }