1、pom
<dependency> <groupId>com.ibeetl</groupId> <artifactId>beetl</artifactId> <version>3.3.2.RELEASE</version> </dependency>
2、java test
import cn.hutool.core.io.file.FileReader; import cn.hutool.core.util.XmlUtil; import org.beetl.core.Configuration; import org.beetl.core.GroupTemplate; import org.beetl.core.Template; import org.beetl.core.resource.ClasspathResourceLoader; import org.beetl.core.resource.StringTemplateResourceLoader; import org.w3c.dom.Document; import java.io.IOException; import java.util.Map; public class BeetlTest { public static void main(String[] args) throws IOException { //默认UTF-8编码,可以在构造中传入第二个参数做为编码 FileReader fileReader = new FileReader("his.txt"); String xml = fileReader.readString(); Map<String,Object> map=XmlUtil.xmlToMap(xml); //初始化代码 ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("org/beetl/hello"); Configuration cfg = Configuration.defaultConfiguration(); GroupTemplate gt = new GroupTemplate(resourceLoader, cfg); //获取模板 Template t = gt.getTemplate("/hello.txt"); t.binding("xml", xml); //渲染结果 String str = t.render(); System.out.println(str); } }
3、hello.txt模板写法
<% var map= @org.quartz.util.XmlToJson.xmlToMap(xml); var xml=map['soap:Body']['ns2:sendMessageResponse']['return']; var xmlMap=@org.quartz.util.XmlToJson.xmlToMap(xml); var list=[]; if(xmlMap['code']=='00000'){ var temp=xmlMap['returnContents']['returnContent']['orderItems']; list=@org.quartz.util.XmlToJson.toList(temp); }else{ } var hisList=list; %> <% for(var i=0;i<list.~size;i++){ var hisOrder={}; hisOrder.username=list[i].payType; hisOrder.password=list[i].settlementType; hisList[i]=hisOrder; } var json=@org.quartz.util.XmlToJson.toJsonString(hisList); print(json); %>
4、XmlToJson类
package org.quartz.util; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.XmlUtil; import cn.hutool.json.JSONUtil; import org.quartz.bean.User; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; public class XmlToJson { public static Map<String,Object> xmlToMap(String xml){ return XmlUtil.xmlToMap(xml); } public static ArrayList<Object> toList(Object object){ if(object instanceof List){ return (ArrayList<Object>) object; } return CollectionUtil.toList(object); } public static User newUser(){ return new User(); } public static String toJsonString(Object object){ return JSONUtil.toJsonStr(object); } }