当我运行这段代码时:
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>
哪个是正确的,所以我的问题是为什么它会将 Employee 更改为 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) lead,我们有一个扩展,允许您覆盖您可能感兴趣的默认名称转换算法:
关于java - JAXB Java 生成 XML,为什么小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918762/