【问题标题】:How to remove XmlRootElement wrapper while marshalling in JAXB如何在 JAXB 中编组时删除 XmlRootElement 包装器
【发布时间】:2017-11-16 09:31:55
【问题描述】:

假设我有以下 POJO 类,我想使用 JAXB 编组

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
Class Employee {
  private String firstName;
  private String lastName;
  private int age;
}

现在我正在使用以下代码 sn-p 编组 Employee 类的实例

JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(employee, os);

生成的 XML 看起来像

<Employee>
  <firstName>Mark</firstName>
  <lastName>Smith</lastName>
  <age>30</age>
</Employee>

问题:我不希望员工数据周围有默认的员工标签。 即

我想要输出如下

 <firstName>Mark</firstName>
  <lastName>Smith</lastName>
  <age>30</age>

如何做到这一点?

【问题讨论】:

    标签: java xml jaxb marshalling


    【解决方案1】:

    不知道你在问什么。 XML 文档必须包含根元素。 您可以使用 QName 更改它(下面的示例),但它必须存在。

    JAXBContext jc = JAXBContext.newInstance(Employee.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    QName qName = new QName("", "whatever");
    JAXBElement<Employee> newRootEmployee = new JAXBElement<Employee>(qName, Employee.class, employee);
    OutputStream os = new FileOutputStream("C:\\employee.xml")
    marshaller.marshal(newRootEmployee , os);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 2012-09-12
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多