2

I need to deserialize xml which is result of polymorphic classes. Below are 2 examples.

Example 1:

<Root>
  <TYPE>TYPE1</TYPE>
  <Data>
    <data1>fdfdf</data1>
    <data2>dfdfdf<data2>
  </Data>
</Root>

Example 2:

<Root>
  <TYPE>TYPE2</TYPE>
  <Data>
   <data3>fdfdf</data1>
  <data4>dfdfdf<data2>
  </Data>
</Root>

My java class structure is

class Root {
 String  TYPE ;
 Data data;

}

class Data {
}

class DataType1 extends Data{
  data1;
  data2;
}

class DataType2 extends Data{
  data3;
  data4;
}

Root.TYPE in xml could be used to determine if the data in xml is for for DataType1 or DataType2. XML does not provide any "class" attribute for tag.

I was trying various Strategy classes from simple xml but could not make it work.

Do you have any suggestion how/which strategy or other classes I should use so that I could correctly parse the xml and create proper object's of DataType1 OR DataType2 during deserialization.

Thanks,

Tushar

Stefan
  • 14,530
  • 4
  • 55
  • 62
Tushar
  • 1,607
  • 1
  • 16
  • 27
  • Have you thought about simply reading the value of type in XML and using a switch statement. – Ali Khalid Mar 14 '12 at 16:19
  • My intention is to generate correct object of class DataType1 or DataType2 when parsing of XML is completed. When I try to parse xml with current class structure I get error message "org.simpleframework.xml.core.ElementException: Element 'data1' does not have a match in class com.test.xml.Data at line 1" – Tushar Mar 15 '12 at 08:50

1 Answers1

1

As @alykhalid said in the comment you should consider to use simple if-else or switch statement.

alexsmail
  • 5,661
  • 7
  • 37
  • 57