假设我有这样的XML:
<host name="myHost">
<service>
<type>TYPE1</type>
<field1>The content of field 1</field1>
</service>
<service>
<type>TYPE2</type>
<field2>The content of field 2</field2>
</service>
</host>
有一种方法(使用JAXB / XStream)说“当你在TYPE1中找到服务中的元素时使用Type1的POJO /当你在TYPE2中找到一个服务元素时,使用一个类型为2的POJO ?
我需要使用它来使用泛型标记,此标记的类型将在解组过程中使用的POJO类有所不同
答案 0 :(得分:0)
使用XStream - &gt;如果服务是列表对象,您将能够以这种格式进行...
<Host>
<name>myHost</name>
<service>
<Child1>
<type>TYPE1</type>
<field1>The content of field 1</field1>
</Child1>
<Child2>
<type>TYPE2</type>
<field2>The content of field 2</field2>
</Child2>
</service>
</Host>
&#13;
代码从这里开始
public class BaseObj {
private String type; }
public class Child1 extends BaseObj {
private String field1;
}
public class Child2 extends BaseObj{
private String field2;
}
public class Host {
private String name;
private List<BaseObj> service
}
public class TestXStream {
public static void main(String[] args) {
List<BaseObj> objects = new ArrayList<BaseObj>();
Child1 obj1 = new Child1();
obj1.setType("TYPE1");
obj1.setField1("The content of field 1");
Child2 obj2 = new Child2();
obj2.setType("TYPE2");
obj2.setField2("The content of field 2");
objects.add(obj1);
objects.add(obj2);
Host host = new Host();
host.setName("myHost");
host.setService(objects);
try {
File test = new File("C:/resources/test_id.xml");
new XStream().toXML(host, new FileOutputStream(test));
} catch (Exception e) {
e.printStackTrace();
}
}