1

I have an XML file in the following form:

<persons>
  <person>
    <firstname>John</firstname>
    <lastname>Doe</lastname>
    <function>manager</function>
    <salary>4000.0</salary>
 </person>
 <person>
   <firstname>Mary</firstname>
   <lastname>Jones</lastname>
   <function>employee</function>
 </person>
<person>

I want to read them into Java Objects depending on their function: if function=manager, then a new Manager() should be created, otherwise an new Employee should be created.

Manager is a subclass of Employee. The classes look like the following:

public class Employee {
     private String firstName;
     private String lastName;
     private String function;

    // getters and setters 
 }

 public class Manager extends Employee {
      private double salary;
      // getters and setter
 }

I already tried using @XmlCustomizer, combination of @XmlDiscrimitatorNode and @XmlDiscriminatorValue and so on, but I can't get it to work. All examples I find are in the form where you want to map 2 subclasses that extend a 3rd one, but never when you want to map superclass and subclass together. Can somebody help me?

  • I'm not sure what are you trying to achieve. It is obvious, and you can't get `Manager` object from using same mechanism how you are doing for `Employee` until you type cast it explicitly. – Ravi Jan 26 '18 at 16:44
  • The manager class has extra methods and 1 extra property that a normal Employee does not have. So you say there is no way to map that immediately from the XML based on the function alone? It was just something I wanted to try out. I did already get it to work when putting the tag around the manager person. If all elements are mapped as person, I can't get the salary anymore (and casting afterwards from new Person() to new Manager() is certainly not normal in Java...) – S. Schillebeeckx Jan 30 '18 at 14:43
  • Here [click](https://stackoverflow.com/questions/2992234/java-jaxb-unmarshall-xml-to-specific-subclass-based-on-an-attribute[) they want to do something similar based on attributes, but they have 1 superclass and 2 subclasses. This didn't work for me... – S. Schillebeeckx Jan 30 '18 at 14:50

0 Answers0