簡體   English   中英

如何在JAXB中編組時刪除XmlRootElement包裝器

[英]How to remove XmlRootElement wrapper while marshalling in JAXB

可以說我有以下POJO類,我想使用JAXB封送它

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

現在,我使用以下代碼片段整理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>

問題:我不希望在員工數據周圍使用默認的Employee標簽。

我想要輸出如下

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

如何實現呢?

不知道你在問什么。 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM