Freemarker:如何将XML放入数据模型?

时间:2013-07-15 18:39:48

标签: java spring spring-mvc freemarker

关注Freemarker documentation

控制器

public ModelAndView home() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("users", userList);
        mav.addObject("user", "Big Joe");
        mav.addObject("title", "Testing initial page, using FreeMarker!");
        try {
            mav.addObject("doc", freemarker.ext.dom.NodeModel.parse (new File("C:\\Users\\Himanshuy\\Desktop\\2.xml")));

        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return mav;
    }

错误

FreeMarker template error: For "${...}" content: Expected a string or something automatically convertible to string (number, date or boolean), but this evaluated to a sequence+hash (wrapper: f.e.dom.NodeListModel): ==> header [in template "index.ftl" at line 13, column 3

FTL

<#assign header=doc.title >
${header}

XML

<book>
  <title>Test Book</title>
  <chapter>
    <title>Ch1</title>
    <para>p1.1</para>
    <para>p1.2</para>
    <para>p1.3</para>
  </chapter>
  <chapter>
    <title>Ch2</title>
    <para>p2.1</para>
    <para>p2.2</para>
  </chapter>
</book>  

我的做法出了什么问题?

2 个答案:

答案 0 :(得分:2)

那应该是doc.book.title(当然你不需要#assign),因为doc是XML文档,它与最顶层的元素不同。 / p>

答案 1 :(得分:0)

我猜您不应该在ftl中使用$ {header},请查看此页面以获取有关如何使用xml文件的更多示例: http://freemarker.org/docs/xgui_imperative_learn.html