📅  最后修改于: 2020-12-04 08:56:58             🧑  作者: Mango
借助CastorMarshaller类的帮助,我们可以使用castor将Java对象编组为xml,反之亦然。它是Marshaller和Unmarshaller接口的实现类。默认情况下,不需要任何其他配置。
您需要创建以下文件,以使用带有Castor的Spring将Java对象编组为XML:
要运行此示例,您需要加载:
下载Spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting,oxm,jdbc,orm等。
如果定义了三个属性id,setter和getter的名称和薪水。
package com.javatpoint;
public class Employee {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
它定义了一个bean castorMarshallerBean,其中Employee类与OXM框架绑定在一起。
它从applicationContext.xml文件获取Marshaller的实例,并调用marshal方法。
package com.javatpoint;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
public class Client{
public static void main(String[] args)throws IOException{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("castorMarshallerBean");
Employee employee=new Employee();
employee.setId(101);
employee.setName("Sonoo Jaiswal");
employee.setSalary(100000);
marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));
System.out.println("XML Created Sucessfully");
}
}
Sonoo Jaiswal
100000.0