- Spring OXM 教程
- Spring OXM - Home
- Spring OXM - 概述
- Spring OXM - 环境设置
- Spring OXM 和 JAXB
- Spring OXM - 创建项目
- Spring OXM - 更新项目 JAXB2
- Spring OXM - 测试 JAXB2
- Spring OXM 和 XStream
- Spring OXM - 更新项目
- Spring OXM - 测试 XStream
- Spring OXM 和 Castor
- Spring OXM - 更新项目
- Spring OXM - 测试 Castor
- Spring OXM 有用资源
- Spring OXM - 快速指南
- Spring OXM - 有用资源
- Spring OXM - 讨论
Spring OXM - 测试 JAXB2
使用编组器和解组器对象创建主类 OXMApplication.java。此类的目的是使用编组器对象将一个学生对象编组为 student.xml,然后使用解组器对象将 student.xml 解组为学生对象。
示例
OXMApplication.java
package com.tutorialspoint.oxm;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import com.tutorialspoint.oxm.model.Student;
public class OXMApplication {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshaller");
Unmarshaller unmarshaller = (Unmarshaller)context.getBean("jaxbMarshaller");
// create student object
Student student = new Student();
student.setAge(14);
student.setName("Soniya");
try {
marshaller.marshal(student, new StreamResult(new FileWriter("student.xml")));
System.out.println("Student marshalled successfully.");
FileInputStream is = new FileInputStream("student.xml");
Student student1 = (Student)unmarshaller.unmarshal(new StreamSource(is));
System.out.println("Age: " + student1.getAge() + ", Name: " + student1.getName());
} catch(IOException | XmlMappingException ex) {
ex.printStackTrace();
}
}
}
输出
在 eclipse 中的该文件的正文区域处单击右键,然后选择 以 Java 应用程序运行,再验证输出。
Oct 10, 2021 8:48:12 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1e127982: startup date [Sun Oct 10 20:48:12 IST 2021]; root of context hierarchy Oct 10, 2021 8:48:12 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [applicationcontext.xml] Oct 10, 2021 8:48:13 PM org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromClasses INFO: Creating JAXBContext with classes to be bound [class com.tutorialspoint.oxm.model.Student] Student marshalled successfully. Age: 14, Name: Soniya
广告