将 XML 解组为列表示例
解组是将 xml 转换回 java 对象的过程。
让我们看看我们的“Employees”类的例子。
private static void unMarshalingExample() throws JAXBException
{
JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
//We had written this file in marshalling example
Employees emps = (Employees) jaxbUnmarshaller.unmarshal( new File("c:/temp/employees.xml") );
for(Employee emp : emps.getEmployees())
{
System.out.println(emp.getId());
System.out.println(emp.getFirstName());
}
}
模型类
我创建了一个模型类 Employee,它有一些常见的字段。
我想构建可以解析一组 employees的代码。
请注意,JAXB 需要在我们将要编组或者解组的最顶层类上添加 @XmlRootElement注释。
ArrayList类是集合框架的一部分,它没有任何 JAXB 注释。
所以我们需要有另一个类“Employees”来代表雇员的集合。
现在在这个类中我们可以添加我们喜欢的任何注释。
@XmlRootElement(name = "employee")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employee
{
private Integer id;
private String firstName;
private String lastName;
private double income;
//Getters and Setters
}
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employees")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employees
{
@XmlElement(name = "employee")
private List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
JAXB Maven 依赖
要运行 JAXB 示例,我们需要添加运行时 maven 依赖项,如下所示:
<dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.2.8-b01</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.2-promoted-b65</version> </dependency>
欢迎来到之路教程(on itroad-com)
元组列表到 XML 示例
编组是“将 java 对象转换为 xml 表示”。
在下面的示例代码中,我首先在控制台中写入“员工”列表,然后在文件中写入。
//Initialize the employees list
static Employees employees = new Employees();
static
{
employees.setEmployees(new ArrayList<Employee>());
//Create two employees
Employee emp1 = new Employee();
emp1.setId(1);
emp1.setFirstName("JackLi");
emp1.setLastName("Gupta");
emp1.setIncome(100.0);
Employee emp2 = new Employee();
emp2.setId(2);
emp2.setFirstName("John");
emp2.setLastName("Mclane");
emp2.setIncome(200.0);
//Add the employees in list
employees.getEmployees().add(emp1);
employees.getEmployees().add(emp2);
}
private static void marshalingExample() throws JAXBException
{
JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//Marshal the employees list in console
jaxbMarshaller.marshal(employees, System.out);
//Marshal the employees list in file
jaxbMarshaller.marshal(employees, new File("c:/temp/employees.xml"));
}
日期:2020-09-17 00:09:41 来源:oir作者:oir
