FreeMarker模版访问XML文件

FreeMarker模版访问XML文件


我这里写了一个简单的xml

<?xml version="1.0" encoding="UTF-8"?>
<love>
    <siteName>爱美依商城</siteName>
    <siteURL name="url" value="https://www.bugkong.com" />
	<siteFL>
	    <FLA>分类A</FLA>
	    <FLB>分类B</FLB>
	</siteFL>
	<siteFL>
	    <FLA>分类C</FLA>
	    <FLB>分类D</FLB>
	</siteFL>
</love>

然后在控制器我们这样做

我这里只列出相关具体的控制器



@RequestMapping("/index5")
public String init5(HttpServletRequest request, HttpServletResponse response,ModelMap model){
	NodeModel nm = null;
	try {
		nm = NodeModel.parse(new File("workspace\\freemarker\\src\\main\\java\\LoveBN.xml"));
	} catch (SAXException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ParserConfigurationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
	model.addAttribute("compute",new CustomPageCounts());
	model.addAttribute("doc",nm);
	return "aaa/index5";
}
接下来我们就可以在我们的模版文件这样使用了


<#recurse doc>获得这个资源文件

<#macro love>love节点

${.node.siteName} 得到siteName的值

${.node.siteFL[0].FLA} 得到第一个siteFL子节点FLA的值


你还可以直接通过传递过来的变量doc来处理

${doc.love.siteFL[0].FLA}<br />
${doc.love.siteFL[2].FLB!"No mouse."}
你还可以将获得的节点进行遍历

<#list doc.love.siteFL as sfk>
${sfk.FLA}<br>
</#list>

完整的代码如下


<#recurse doc>
<#macro love>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>freemarker-${.node.siteName}</title>
</head>
<body>
${doc.love.siteFL[0].FLA}<br />
${doc.love.siteFL[2].FLB!"No mouse."}<br />
${.node.siteFL[0].FLA}<br />
<br>
<#list doc.love.siteFL as sfk>
 ${sfk.FLA}<br>
</#list>

</body>
</html>
</#macro>



爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img