I have a xml with format say
<x>
<y>
<z Name="z"> File Explorer </z>
</y>
</x>
I want to write a freemarker template to retrieve the content "File Explorer". I have written java code to transform xml to html. input xml is given 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
<span>${doc["x/y/z[@Name='z']"/]}</span>
But this on transforming displays ${doc["x/y/z[@Name='z']"/]} instead of
File Explorer
Use the Freemarker Ant task freemarker.ext.ant.FreemarkerXmlTask
:
lib
folder which includes the freemarker JAR file location
attribute of the pathElement
element of the Ant task basedir
in the freemarker
element of the Ant task template
attribute of the freemarker
element of the Ant task For example:
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:
<?xml version="1.0"?>
<root name="test" value="123">
<child name="data" value="456"/>
</root>
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
Then run ant
from the directory which contains the build.xml
file.
References
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.