Spring Object / XML映射示例

Spring的对象/ XML映射正在将对象转换为XML,反之亦然。 此过程也称为

  1. XML编组 –将对象转换为XML。
  2. XML解组 –将XML转换为对象。

在本教程中,我们向您展示如何使用Spring的oxm进行对象XML转换。

注意
废话,关于使用Spring的oxm的原因和好处,请阅读此官方的Spring Object / XML映射文章。

1.项目依赖

此示例中的依赖项。

注意
Spring的oxm本身不处理XML编组或UnMarshalling,它依赖于开发人员注入他们偏爱的XML绑定框架。 在这种情况下,您将使用Castor绑定框架。

<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>

	<dependencies>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- spring oxm -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Uses Castor for XML -->
		<dependency>
			<groupId>org.codehaus.castor</groupId>
			<artifactId>castor</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Castor need this -->
		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xercesImpl</artifactId>
			<version>2.8.1</version>
		</dependency>

	</dependencies>

2.简单对象

一个简单的对象,以后将其转换为XML文件。

package com.mkyong.core.model;

public class Customer {

	String name;
	int age;
	boolean flag;
	String address;

	//standard getter, setter and toString() methods.
}

3.编组和编组

此类将通过Spring的oxm接口( MarshallerUnmarshaller处理转换。

package com.mkyong.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class XMLConverter {

	private Marshaller marshaller;
	private Unmarshaller unmarshaller;

	public Marshaller getMarshaller() {
		return marshaller;
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public Unmarshaller getUnmarshaller() {
		return unmarshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

	public void convertFromObjectToXML(Object object, String filepath)
		throws IOException {

		FileOutputStream os = null;
		try {
			os = new FileOutputStream(filepath);
			getMarshaller().marshal(object, new StreamResult(os));
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	public Object convertFromXMLToObject(String xmlfile) throws IOException {

		FileInputStream is = null;
		try {
			is = new FileInputStream(xmlfile);
			return getUnmarshaller().unmarshal(new StreamSource(is));
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

}

4.弹簧配置

在Spring的bean配置文件中,注入CastorMarshaller作为XML绑定框架。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="XMLConverter" class="com.mkyong.core.XMLConverter">
		<property name="marshaller" ref="castorMarshaller" />
		<property name="unmarshaller" ref="castorMarshaller" />
	</bean>
	<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" />

</beans>

5.测试

运行。

package com.mkyong.core;

import java.io.IOException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.core.model.Customer;

public class App {
	private static final String XML_FILE_NAME = "customer.xml";
	
	public static void main(String[] args) throws IOException {
		ApplicationContext appContext = new ClassPathXmlApplicationContext("App.xml");
		XMLConverter converter = (XMLConverter) appContext.getBean("XMLConverter");
		
		Customer customer = new Customer();
		customer.setName("mkyong");
		customer.setAge(30);
		customer.setFlag(true);
		customer.setAddress("This is address");
		
		System.out.println("Convert Object to XML!");
		//from object to XML file
		converter.convertFromObjectToXML(customer, XML_FILE_NAME);
		System.out.println("Done \n");
		
		System.out.println("Convert XML back to Object!");
		//from XML to object
		Customer customer2 = (Customer)converter.convertFromXMLToObject(XML_FILE_NAME);
		System.out.println(customer2);
		System.out.println("Done");
		
	}
}

输出量

Convert Object to XML!
Done 

Convert XML back to Object!
Customer [name=mkyong, age=30, flag=true, address=This is address]
Done

在项目根文件夹中生成以下XML文件“ customer.xml ”。

文件:customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<customer flag="true" age="30">
	<address>This is address</address>
	<name>mkyong</name>
</customer>

Castor XML映射

等等,为什么将标志和年龄转换为属性? 这是控制将哪个字段用作属性或元素的方法吗? 当然,您可以使用Castor XML映射定义对象和XML之间的关系。

创建以下映射文件,并将其放入您的项目类路径中。

文件:mapping.xml

<mapping>
	<class name="com.mkyong.core.model.Customer">

		<map-to xml="customer" />

		<field name="age" type="integer">
			<bind-xml name="age" node="attribute" />
		</field>

		<field name="flag" type="boolean">
			<bind-xml name="flag" node="element" />
		</field>

		<field name="name" type="string">
			<bind-xml name="name" node="element" />
		</field>

		<field name="address" type="string">
			<bind-xml name="address" node="element" />
		</field>
	</class>
</mapping>

在Spring bean配置文件中,通过“ mappingLocation ”将上方mapping.xml注入CastorMarshaller中。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="XMLConverter" class="com.mkyong.core.XMLConverter">
		<property name="marshaller" ref="castorMarshaller" />
		<property name="unmarshaller" ref="castorMarshaller" />
	</bean>
	<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" >
		<property name="mappingLocation" value="classpath:mapping.xml" />
	</bean>

</beans>

再次测试,XML文件“ customer.xml ”将被更新。

文件:customer.xml

<?xml version="1.0" encoding="UTF-8"?>
<customer age="30">
	<flag>true</flag>
	<name>mkyong</name>
	<address>This is address</address>
</customer>

下载源代码

下载它– Spring3-Object-XML-Mapping-Example.zip (7 KB)

参考文献

  1. Castor XML映射
  2. Spring对象/ XML映射参考

翻译自: https://mkyong.com/spring3/spring-objectxml-mapping-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring项目中,我们可以通过使用Spring Web Services框架来创建Web服务。在返回指定XML样式数据方面,我们可以使用Spring的消息转换器(Message Converters)来实现。 以下是一个示例代码,演示如何使用Spring Web Services框架和消息转换器来返回XML格式的数据: ```java import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MyWebService { @RequestMapping(value = "/my-webservice", produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public MyResponseObject myWebServiceMethod() { MyResponseObject response = new MyResponseObject(); // populate response object return response; } } ``` 在上面的示例代码中,我们使用 @RequestMapping 注解来映射一个Web服务方法。我们指定了 produces 参数来指定响应的内容类型为 XML。我们还使用 @ResponseBody 注解来指示Spring将返回值转换为XML格式并作为响应体发送。 需要注意的是,要使用消息转换器,需要在Spring的配置文件中添加以下配置: ```xml <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"> <property name="supportedMediaTypes" value="application/xml" /> </bean> </list> </property> </bean> ``` 在上面的配置中,我们添加了一个用于转换XML格式的消息转换器。这个转换器将会被RequestMappingHandlerAdapter自动识别,并用于将响应转换为XML格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值