使用freemarker生成xml模板

今天在java交流群里有个人问我如何用freemarker生成xml模板文件,可以手动配置参数,于是我到网上百度了一下。发现有一位同行的博文写的很nice,于是我就照着他的代码敲了一遍,最后实现了,本想贴出他的uri的,但是找不到了。网上这样的例子很多,大家可以自己到网上看看,我的建议是一个问题多看几个解决方案,这样才能找到正确的或者是最优解。


其实要实现的功能就是简单的将红框中的内容简单替换

下面是java代码:

package createxml;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
    
public class XMLTest {    
        
    private Configuration configuration = null;    
        
    public XMLTest(){    
        configuration = new Configuration();    
        configuration.setDefaultEncoding("UTF-8");    
    }    
        
    public static void main(String[] args) {    
    	XMLTest test = new XMLTest();    
        test.createWord();    
    }  
    
    public void createWord(){    
        Map<String,Object> dataMap=new HashMap<String,Object>();    
        getData(dataMap);    
        configuration.setClassForTemplateLoading(this.getClass(), "/createxml");  //FTL文件所存在的位置,我的只能放在与java相同的包下    
        Template t=null;    
        try {    
            t = configuration.getTemplate("xmltemp.ftl"); //文件名    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
        File outFile = new File("G:/outFilessa"+Math.random()*10000+".xml");  //生成文件的路径  
        Writer out = null;    
        try {    
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));    
        } catch (FileNotFoundException e1) {    
            e1.printStackTrace();    
        }    
             
        try {    
            t.process(dataMap, out);    
        } catch (TemplateException e) {    
            e.printStackTrace();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
    }    
    //这里赋值的时候需要注意,xml中需要的数据你必须提供给它,不然会报找不到某元素错的.  
    private void getData(Map<String, Object> dataMap) {    
        dataMap.put("domaintype", "mytype");    
    }    
} 
然后是模板文件:


<domain type='${domaintype}'> 
	<name>bjsxtvm03</name>
	<memory unit='KiB'>1048576</memory>
	<currentMemory unit='KiB'>1048576</currentMemory>
	<vcpu placement='static'>1</vcpu>
	<os>
		<type arch='x86_64' machine='rhel6.6.0'>hvm</type>
		<boot dev='hd'/>
		</os>
	<features>
		<acpi/><apic/>
		<pae/>
	</features>
	<clock offset='utc'/>
	<on_poweroff>destroy</on_poweroff>
	<on_reboot>restart</on_reboot>
	<on_crash>restart</on_crash>
	<devices>
		<emulator>/usr/libexec/qemu-kvm</emulator>
		<disk type='file' device='disk'>
			<driver name='qemu' type='qcow2' cache='none'/>
			<source file='/kvmtest/centos-6.6-04.qcow2'/>
			<target dev='vda' bus='virtio'/>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
		</disk>
		<disk type='block' device='cdrom'>
			<driver name='qemu' type='raw'/>
			<target dev='hdc' bus='ide'/>
			<readonly/>
			<address type='drive' controller='0' bus='1' target='0' unit='0'/>
		</disk>
		<controller type='usb' index='0' model='ich9-ehci1'>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x7'/>
		</controller>
		<controller type='usb' index='0' model='ich9-uhci1'>
			<master startport='0'/>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0' multifunction='on'/>
		</controller>
		<controller type='usb' index='0' model='ich9-uhci2'>
			<master startport='2'/>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x1'/>
		</controller>
		<controller type='usb' index='0' model='ich9-uhci3'>
			<master startport='4'/>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x2'/>
			</controller>
		 <controller type='ide' index='0'>
		 	<address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
		 </controller>
		<interface type='network'>
			<source network='default'/>
			<model type='virtio'/>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
		</interface>
		<serial type='pty'>
			<target port='0'/>
		</serial>
		<console type='pty'>
			<target type='serial' port='0'/>
		</console>
		<input type='tablet' bus='usb'/>
		<input type='mouse' bus='ps2'/>
		<graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0'>
			<listen type='address' address='0.0.0.0'/>
		</graphics>
		<video>
			<model type='cirrus' vram='9216' heads='1'/>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
		</video>
		<memballoon model='virtio'>
			<address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
		</memballoon>
	</devices>
</domain>
这里要说明几点的是:

1,我自己测试的时候只能将模板文件放在java的包下,也就是和java同一个地方。


Java 中使用 Freemarker 生成 XML 文件,需要先添加依赖。 Maven 依赖: ```xml <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` Gradle 依赖: ```groovy implementation 'org.freemarker:freemarker:2.3.31' ``` 接下来,我们可以编写 Freemarker 模板文件 `template.ftl`,用于生成 XML。 示例模板文件: ```xml <?xml version="1.0" encoding="UTF-8"?> <root> <user id="${user.id}" name="${user.name}"> <age>${user.age}</age> </user> </root> ``` 然后,我们可以编写 Java 代码,使用 Freemarker 解析模板文件,并将所需数据填充到模板中,生成 XML 文件。 示例 Java 代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class FreemarkerXmlGenerator { public static void main(String[] args) throws IOException, TemplateException { // 创建 Configuration 实例 Configuration configuration = new Configuration(Configuration.getVersion()); // 设置模板文件所在目录 configuration.setDirectoryForTemplateLoading(new File("/path/to/template/dir")); // 加载模板文件 Template template = configuration.getTemplate("template.ftl"); // 准备数据 Map<String, Object> data = new HashMap<>(); data.put("user", new User(1, "Tom", 20)); // 创建输出文件 File outputFile = new File("/path/to/output/file.xml"); FileWriter fileWriter = new FileWriter(outputFile); // 填充数据并生成 XML 文件 template.process(data, fileWriter); // 关闭输出流 fileWriter.close(); } private static class User { private int id; private String name; private int age; public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } } } ``` 以上代码中,我们通过 `Configuration` 类加载模板文件,然后用 `Template` 类进行解析和填充,并将结果输出到指定的文件中。注意要在最后关闭输出流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值