当我运行这个代码:
import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; public class JavaToXMLDemo { public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Employee.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); Employee object = new Employee(); object.setCode("CA"); object.setName("Cath"); object.setSalary(300); m.marshal(object,System.out); } } @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) class Employee { private String code; private String name; private int salary; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int population) { this.salary = population; } }
我得到
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee> <code>CA</code> <name>Cath</name> <salary>300</salary> </employee>
这是正确的,所以我的问题是为什么把员工改为员工?
是否可以使用大写字母E打印,而不是使用员工?
这是我实际想要的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Employee> <code>CA</code> <name>Cath</name> <salary>300</salary> </Employee>
谢谢!
解决方法
您所看到的行为是标准的
JAXB (JSR-222) XML名称到Java名称转换算法的结果.
您可以使用@XmlRootElement注释来指定名称:
@XmlRootElement(name="Employee") @XmlAccessorType(XmlAccessType.FIELD) class Employee { ... }
我是EclipseLink JAXB (MOXy)领先,我们有一个扩展,它允许你覆盖,你可能会感兴趣的默认名称转换算法:
> http://blog.bdoughan.com/2011/05/overriding-jaxbs-name-mangling.html