【发布时间】:2023-03-17 22:00:01
【问题描述】:
我必须在我的程序中使用 JAXB 生成以下 xml。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee empId="12345">
<name>ABC</name>
<address type="Residence">Bangalore</address>
</Employee>
我必须使用 JAXB 生成上述 xml。 我的 Employee 类如下:
员工类
package mypack;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement (name = "Employee")
public class Employee {
private String name;
private String address;
private int empId;
private String addressType;
@XmlAttribute
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return addressType;
}
public void setType(String addressType) {
this.addressType = addressType;
}
}
我正在使用 JAXB 来编组对象。
Employee emp = new Employee();
emp.setName("ABC");
emp.setEmpId(12345);
emp.setAddress("Bangalore");
emp.setType("Residence");
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(emp, System.out);
它不会生成所需的 xml。而是按如下方式生成 xml:
**Xml Being Generated**
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee empId="12345">
<name>ABC</name>
<address>Bangalore</address>
<type>Residence</type>
</Employee>
其实我不知道怎么注释type属性,这样我就会生成xml为<address type="Resident">Bangalore</address>
我的 Employee 类应该像上面那样吗?如果是,那么如何注释 type 属性,使其成为<address> 标签中的属性。
请帮帮我。
【问题讨论】:
-
您是否考虑过创建模式并使用 XJC 来创建您的 java 类?在您的架构中,您可以设置所需的所有属性和值。
-
如果我从 xml 生成 java 类,Schema 将很有用。但我的要求是我必须生成从 java 对象指定的 xml。我的意思是说 java 到 xml,而不是相反。而且我不必担心 xml,因为在我的情况下,xml 不需要具有架构。谢谢
-
仅供参考,如果您朝任一方向前进,都可以使用模式。即使我不需要,我发现使用模式来定义 XML 的格式并让 XJC 为我创建适合 JaxB 的 Java 类也很有帮助。我发现这比自己编写 JaxB 更容易。但这只是我。
-
我同意。但是我没有任何 xsd 文件,因此我可以使用它来生成 java 类。我其实什么都没有。我的要求是按照上面的格式生成 xml 文件。我该如何进行?再次感谢。
-
这就是我的观点。创建一个 xsd 文件并让它创建 Java 类,而不是自己创建类。您可以选择,您可以手动创建类,也可以创建 xsd 并让 XJC 从 xsd 创建类。就个人而言,鉴于需要生成具有某种格式的 xml 文件,我宁愿花精力创建 xsd。
标签: java jaxb marshalling unmarshalling jaxb2