`
enjiex
  • 浏览: 67282 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Velocity Template的另类用法:生成XML

阅读更多
前一段有应用中有个场景,是远程调用时,需要给对方传入xml格式的数据。一般生成xml的话,或者使用DOM4J等操作xml的第三方软件包,一个节点一个节点的生成xml格式数据;亦或者高级一些,使用反射,动态生成节点及数据。
上面第一种方式因为在程序中手动控制节点,所以可以生成较为复杂的结构;但也存在相应的问题,及数据与格式绑定太死,若需要生成多个xml数据,则可能会重复很种实现。上述的第二种方式刚好解决了上面说的重复实现的缺点,但最好的使用场景是xml中数据的数据结构刚好和对象、属性及其嵌套对象之间一致的话,实现起来较为方便。当然这并不是说不能用来生成较复杂的xml格式,但可能要做较多的工作。
除了上面说的,这里还有一种应该是比较非主流的实现方式吧,即使用Velocity中Template来做。之前只以为是Template是返回给页面的,那天经同事指点,竟然还有如此妙用。这里也仅仅依赖velocity的包,所以也不算太麻烦。费话不多说了,先看示例吧。
首先创建项目及添加依赖,pom文件如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.nuc.template2xml</groupId>
	<artifactId>template2xml</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>template2xml</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
			<version>1.6.3</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

我们除了用maven创建项目时会自动依赖的junit,我们仅仅添加了对velocity的依赖。
在使用的时候,也并不复杂,只需要对Velocity进行初始化,创建VelocityContext,获得模板文件位置,差不多就可以了,如下:
 public static void main( String[] args )
    {
    	try {
    		UserInfo userInfo = buildUserInfo();
    		
			Properties p = new Properties();
			p.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			
			Velocity.init(p);
			Template template = Velocity.getTemplate("vm/userInfo.vm");
			Context context = new VelocityContext();
			context.put("request", userInfo);
			StringWriter sw = new StringWriter();
			template.merge(context, sw);
			System.out.println(sw.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    }   


下面是模板文件
<?xml version="1.0" encoding="UTF-8"?>
<PACKET TYPE="REQUEST">
    <HEAD>
    	<VERSION>R1</VERSION>
    </HEAD>
    <BODY>
    	<BASE>
    		<USERNAME>$!request.name</USERNAME>
			<AGE>$!request.age</AGE>
			<SEX>$!request.sex</SEX>
    	</BASE>
    	<DETAILS>
    		<PAYINFO>
    			<ACCOUNTID>$!request.account.id</ACCOUNTID>
				<MONEY>$!request.account.money</MONEY>
    		</PAYINFO>
    	</DETAILS>
    </BODY>
</PACKET>

模板文件也就是一个普通的xml文件,不同的是使用了Velocity的标签“$!”。
通过上面简单的步骤,步能生成我们需要的xml格式的字符串了。详细过程见附件。

这种方式生成xml格式字符串也不是万能的,因为必须自定义xml模板文件。不过在一些场景中倒也不失为一种选择。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics