[英]Freemarker template engine to retrieve data from xml
I have a xml with format say 我有一个格式说的xml
<x>
<y>
<z Name="z"> File Explorer </z>
</y>
</x>
I want to write a freemarker template to retrieve the content "File Explorer". 我想编写一个freemarker模板来检索内容“文件资源管理器”。 I have written java code to transform xml to html. 我已经编写了Java代码将xml转换为html。 input xml is given xml. 输入xml就是xml。
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setDefaultEncoding("UTF-8");
InputSource inputSource = new InputSource( new StringReader(xml.asXML()));
root.put("doc", freemarker.ext.dom.NodeModel.parse(inputSource));
result = new StringWriter();
template.process(root, result);
I tried freemarker template with xpath 我用xpath尝试了freemarker模板
<span>${doc["x/y/z[@Name='z']"/]}</span>
But this on transforming displays ${doc["x/y/z[@Name='z']"/]} instead of 但这在转换时显示$ {doc [“ x / y / z [@ Name ='z']” /]}而不是
File Explorer 文件管理器
Use the Freemarker Ant task freemarker.ext.ant.FreemarkerXmlTask
: 使用Freemarker Ant任务freemarker.ext.ant.FreemarkerXmlTask
:
lib
folder which includes the freemarker JAR file 转到包含freemarker JAR文件的lib
文件夹 location
attribute of the pathElement
element of the Ant task 将其粘贴到Ant任务的pathElement
元素的location
属性中 basedir
in the freemarker
element of the Ant task 将其粘贴到Ant任务的freemarker
元素中的基于basedir
的属性中 template
attribute of the freemarker
element of the Ant task 将其粘贴到Ant任务的freemarker
元素的template
属性中 For example: 例如:
build.xml: build.xml文件:
<?xml version="1.0"?>
<project basedir="." default="generate" name="FreeMarker-FAQ">
<taskdef name="freemarker" classname="freemarker.ext.ant.FreemarkerXmlTask">
<classpath>
<fileset dir="lib">
<include name="freemarker.jar"/>
</fileset>
</classpath>
</taskdef>
<target name="generate">
<mkdir dir="html"/>
<freemarker basedir="." template="xml2html.ftl" includes="xml/data.xml" destdir="html"/>
</target>
</project>
data.xml: data.xml中:
<?xml version="1.0"?>
<root name="test" value="123">
<child name="data" value="456"/>
</root>
xml2html.ftl xml2html.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<title>${.node.root.@name}</title>
<meta name="keywords" content="FreeMarker, Java, servlet, HTML, template, free software, open source, XML" />
</head>
<body bgcolor="#ffffff">
<h2><a name="top">${.node.root.child.@name}.</a></h2>
</body>
</html>
Directory structure 目录结构
build.xml build.xml文件
Then run ant
from the directory which contains the build.xml
file. 然后从包含build.xml
文件的目录中运行ant
。
References 参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.