如何将数据从xml填充到JavaBean类

如何将数据从xml填充到JavaBean类,java,xml,jaxb,Java,Xml,Jaxb,我想将所有xml数据填充到JavaBean类中 <employee> <empId>a01</empId> <dptName>dev</dptName> <person> <name>xyz</name> <age>30</age> <phone>123456</phone>

我想将所有
xml
数据填充到JavaBean类中

<employee>
    <empId>a01</empId>
    <dptName>dev</dptName>
    <person>
        <name>xyz</name>
        <age>30</age>
        <phone>123456</phone>
    </person>
</employee>
我认为这可以通过使用
JAXB
实现,但是如何实现呢


注意:此外,我必须将数据保存到数据库中。

使用


在这里,您可以找到没有任何注释的文档

,您可以使用这些文档执行以下自Java SE 6以来包含在JDK/JRE中的操作:

无注释 您的模型似乎匹配映射到您发布的XML所需的所有默认命名规则。这意味着您可以使用您的模型,而无需以注释的形式添加任何元数据。需要注意的一点是,如果不指定元数据来将根元素与类关联,则在编组时,需要在解组时指定
Class
参数,并在
JAXBElement
的实例中包装根对象

演示

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);
在下面的演示代码中,我们将把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);
演示

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);
了解更多信息


您可以简单地解析xml,提取“节点文本”,并通过创建它们的实例分配给变量(您可能还需要getter setter)。
@XmlRootElement
class Employee {
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);