Java如何在JAXB中更改XML根元素名称?
在以下代码片段中,您将学习如何更改JAXBAPI生成的XML的默认根元素名称。默认情况下,该类的名称用作根元素名称。要更改根元素名称,我们可以使用注释的name属性@XmlRootElement。在Customer下面的模型中,我们将根元素名称更改为cust。
package org.nhooo.example.jaxb; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "cust") @XmlType(propOrder = {"id", "name", "address"}) public class Customer { private Integer id; private String name; private Address address; @XmlElement public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @XmlElement public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
当使用JAXBAPI将此POJO转换为XML时,将得到以下结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <cust> <id>1</id> <name>Johnny Mnemonic</name> <address> <street>Sunset Road</street> <city>Denpasar</city> <province>Bali</province> <postCode>800000</postCode> <country>Indonesia</country> </address> </cust>