简体   繁体   中英

Freemarker template engine to retrieve data from xml

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 :

  • Go to the lib folder which includes the freemarker JAR file
  • Copy the path
  • Paste it into the location attribute of the pathElement element of the Ant task
  • Copy the path of the XML file
  • Paste it into the attribute basedir in the freemarker element of the Ant task
  • Copy the path of the FTL file
  • Paste it into the template attribute of the freemarker element of the Ant task

For example:

  • Ant task

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>
  • XML file

data.xml:

<?xml version="1.0"?>
<root name="test" value="123">
  <child name="data" value="456"/>
</root>
  • Freemarker Template

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

    • /lib
      • freemarker.jar
    • /html
      • data.html
    • /xml
      • data.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM