-1

Suppose i have an XML like this:

<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>

There is a way (with JAXB / XStream) to say "when you find an element in service with TYPE1 use a POJO that is Type1 / When you find an element in service with TYPE2 use a POJO that is Type2 ?

I will need this to use a generic tag and the type of this tag will make the difference about the POJO class to use in Unmarshalling process

Mistre83
  • 2,677
  • 6
  • 40
  • 77
  • I don't see a question. I do see a statement "There is a way", so if that's true, just use that way. – Andreas Sep 04 '15 at 16:11
  • I've simply forget to add a question mark on bold phrase..... – Mistre83 Sep 04 '15 at 16:14
  • Adding a question mark doesn't make it a question. "Is there ... ?" is a question. --- JAXB can't do that. You'll have to map the data from the class JAXB creates to your POJO classes. Don't know XStream. – Andreas Sep 04 '15 at 16:25

1 Answers1

0

With XStream--> You will be able to do in this format, if the service is a list object...

<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>

Code starts here

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();
        }
    }
Jugunu
  • 141
  • 3
  • 14