如何使用JAXB从XML中删除不需要的根元素?

时间:2018-02-05 09:19:38

标签: xml jaxb tags

如何从通过JAXB生成的XML中删除不需要的根元素?

我需要的是

enter image description here

下面是Pojo类的代码:

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

有没有办法可以删除出现在Employee类中的Emp根元素?

我尝试在Employee类中使用XMLRootElement(name =&#34;&#34;),但它并没有帮助我删除Emp标签。

1 个答案:

答案 0 :(得分:2)

对于你想要的xml:

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

姓名,年龄和部门不属于共同要素。所以你应该让你的POJO像这样:

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

}

并且姓名:

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

年龄:

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

}

部门:

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

}

通用接口EmployeeDetail做得不多:

public interface EmployeeDetail {
}

使用这些POJO,您将能够编组/解组您指定的xml(跳过<pre>)以方便/快速。