我想将所有xml
数据填充到java bean类
<employee>
<empId>a01</empId>
<dptName>dev</dptName>
<person>
<name>xyz</name>
<age>30</age>
<phone>123456</phone>
</person>
</employee>
下面是我想要存储xml
数据的java bean类。
class employee{
private String empId;
private String dptName;
private Person person;
//getter setter below
}
class Person{
String name;
private String age;
private String phone;
//getter setter below
}
我认为这可以使用JAXB
来完成,但是如何?
注意:我还需要将数据保存到数据库中。
答案 0 :(得分:5)
如果没有任何注释,您可以使用自JD SE 6以来JDK / JRE中包含的JAXB (JSR-222)执行以下操作:
您的模型似乎与映射到您发布的XML所需的所有默认命名规则相匹配。这意味着您可以使用模型而无需以注释的形式添加任何元数据。需要注意的一点是,如果您没有指定元数据以将根元素与类关联,那么您需要在解组时指定Class
参数,并在编组时将根对象包装在JAXBElement
的实例中。
<强>演示强>
在下面的演示代码中,我们将XML转换为对象,然后将对象转换回XML。
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Employee> je = unmarshaller.unmarshal(xml, Employee.class);
Employee employee = je.getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(je, System.out);
了解更多信息
JAXBElement
@XmlRootElement
的需要
当一个类使用@XmlRootElement
(或@XmlElementDecl
)与根元素相关联时,在解组或将结果包装在{时,您不需要指定Class
参数编组时{1}}。
<强>员工强>
JAXBElement
<强>演示强>
@XmlRootElement
class Employee {
了解更多信息
答案 1 :(得分:-2)
您可以使用xstream api
轻松完成此操作XStream is a simple library to serialize objects to XML and back again.