summary
summary

Reputation: 125

How to remove unwanted root element from XML using JAXB?

How can I remove unwanted root element from the XML that is being generated through JAXB?

What I need is

enter image description here

below is the code for Pojo classes:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="empType", propOrder={ "name", "age", "deptt"})
@XmlRootElement(name = "")
public class EmpType {


EmpType () {}

public EmpType (String name, String age, String deptt ) {

    this.name=name;
    this.age=age;
    this.deptt=deptt;

}

  @XmlElement(name="name", required=true)
  protected String name;
  @XmlElement(name="age", required=true)
  protected String age;
  @XmlElement(name="deptt", required=true)
  protected String deptt;

      ... getter / setters

}



  @XmlAccessorType(value=javax.xml.bind.annotation.XmlAccessType.FIELD)
  @XmlType(name="employeesType", propOrder={"emp"})

 public class EmployeesType
{
@XmlElement(required=true)
protected List<EmpType> emp;
protected String prolog;

public EmployeesType()
{
}

public List<EmpType> getEmp()
{
    if(emp== null)
    {
        data = new ArrayList<EmpType>();
    }
    return emp;
}

getter/setter for prolog
}

Is there a way where I can remove the Emp root element that is appearing from Employee class?

I tried using XMLRootElement (name ="") in Employee class but it didn't help me in removing Emp tag.

Upvotes: 1

Views: 2167

Answers (1)

martidis
martidis

Reputation: 2975

For the xml you want:

<Employees>
    <prolog>test prolog</prolog>
    <name>employeeOne</name>
    <age>24</age>
    <deptt>store</deptt>
    <name>employeeTwo</name>
    <age>25</age>
    <deptt>store</deptt>
</Employees>

Name, age and department are not part of a common element. So you should have your POJOs like this:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"prolog", "employeeDetails"})
@XmlRootElement(name = "Employees")
public class Employees {


    @XmlElement(name="prolog", required=true)
    protected String prolog;
    @XmlElements({
            @XmlElement(name="name", type = Name.class),
            @XmlElement(name="age", type = Age.class),
            @XmlElement(name="deptt", type = Department.class),
    })
    private List<EmployeeDetail> employeeDetails;

}

And Name:

public class Name implements EmployeeDetail {
    @XmlValue
    private String name;
}

Age:

public class Age implements EmployeeDetail {
    @XmlValue
    private int age;

}

And Department:

public class Age implements EmployeeDetail {
    @XmlValue
    private int age;

}

The common interface EmployeeDetail does not do much:

public interface EmployeeDetail {
}

With these POJOs you will be able to marshal/unmarshal the xml you specified (skipped <pre>) for convenience/speed.

Upvotes: 3

Related Questions