我想将所有xml数据填充到java bean类中,
<employee>
<empId>a01</empId>
<dptName>dev</dptName>
<person>
<name>xyz</name>
<age>30</age>
<phone>123456</phone>
</person>
</employee>
Run Code Online (Sandbox Code Playgroud)
下面是我想要存储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
}
Run Code Online (Sandbox Code Playgroud)
我认为这可以用JAXB但是怎么做?
注意:我还要将数据保存到数据库中.
在没有任何注释的情况下,您可以使用JAXB(JSR-222)执行以下操作,自Java SE 6以来,它包含在JDK/JRE中:
您的模型似乎与映射到您发布的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);
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息
JAXBElement与@XmlRootElement当一个类使用@XmlRootElement(或@XmlElementDecl)与根元素相关联时,您不需要Class在解组时指定参数,也不需要JAXBElement在编组时将结果包装起来.
雇员
@XmlRootElement
class Employee {
Run Code Online (Sandbox Code Playgroud)
演示
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Employee employee = (Employee) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(employee, System.out);
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息
| 归档时间: |
|
| 查看次数: |
4395 次 |
| 最近记录: |