在实际项目中我们经常要使用xml文件,如何通过StringTemplate工具匹配xml 文件,即通过xml模板快速获取目标xml文件,如下是一个小例子。
1.字符串模板工具类,直接看代码StringTemplateUtil.
<span style="font-size:12px;">package com.ilucky.util.template; import org.joda.time.DateTime; import org.stringtemplate.v4.ST; /** * @author IluckySi * @date 20140718 */ public class StringTemplateUtil { private ST stringTemplate; public StringTemplateUtil(String templateXml) { this.stringTemplate = new ST(templateXml,'$','$'); } public StringTemplateUtil add(String key,String value) { this.stringTemplate.add(key,value); return this; } public StringTemplateUtil addHeader(String name){ String time = new DateTime().toString("yyyy/MM/dd HH:mm:ss.SSS"); stringTemplate.add("name",name); stringTemplate.add("time",time); return this; } public String build() { return stringTemplate.render(); } } </span>2.获取xml文件的工具类,直接看代码XmlReadUtil。
<span style="font-size:12px;">package com.ilucky.util.template; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IoUtils; /** * @author IluckySi * @date 20140718 */ public class XmlReadUtil { public String readXml(String path) { String result = null; InputStream is = null; try { is = this.getClass().getResourceAsStream(path); result = IoUtils.toString(is,"UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { IoUtils.closeQuietly(is); } return result; } } </span>3.xml模板文件,直接看代码test.xml.
<span style="font-size:12px;"><?xml version="1.0" encoding="UTF-8"?> <root> <head> <name>$name$</name> <time>$time$</time> </head> <body> <ip>$ip$</ip> <mac>$mac$</mac> </body> </root> </span>4.最后看测试类,直接看代码MainTest。
<span style="font-size:12px;">package com.ilucky.util.template; import org.apache.commons.lang3.StringUtils; /** * @author IluckySi * @date 20140718 */ public class MainTest { public static void main(String[] args) { //获取xml文件中的内容,并将其内容编码为UTF-8. String path = "/com/ilucky/util/template/test.xml"; String templateXml = new XmlReadUtil().readXml(path); //通过StringTemplateUtil工具获取目标xml. StringTemplateUtil util = new StringTemplateUtil(templateXml); util.addHeader("IluckySi"); util.add("ip","127.0.0.1"); util.add("mac","11-22-33-44-55-66"); String result = util.build(); System.out.println("经过字符串模板转换后的xml字符串为: \r\n" + result); //快速获取xml指定位置内容. System.out.println(StringUtils.substringBetween(result,"<name>","</name>")); System.out.println(StringUtils.substringBetween(result,"<time>","</time>")); System.out.println(StringUtils.substringBetween(result,"<ip>","</ip>")); System.out.println(StringUtils.substringBetween(result,"<mac>","</mac>")); } } /** 输出结果: 经过字符串模板转换后的xml字符串为: <?xml version="1.0" encoding="UTF-8"?> <root> <head> <name>IluckySi</name> <time>2014/07/18 20:51:34.597</time> </head> <body> <ip>127.0.0.1</ip> <mac>11-22-33-44-55-66</mac> </body> </root> IluckySi 2014/07/18 20:51:34.597 127.0.0.1 11-22-33-44-55-66 */ </span>原文链接:https://www.f2er.com/xml/298330.html