代码之家  ›  专栏  ›  技术社区  ›  Robert

FreeMarker模板JSON-给它一个节点?下一步查找当前节点是否有同级节点?

  •  1
  • Robert  · 技术社区  · 15 年前

    我想将XML文件转换为JSON。问题是,我有结构

    <node id="1">
        <title>Content ...</title>
    </node>
    
    <node id="2">
        <title>Secon ...</title>
        <subnodes>
    
            <node id="3">
            <title>Secon ...</title>
            <subnodes>
    
                <node id="4">
                    <title>Secon ...</title>
                </node>
    
            </subnodes>
    
        </node>
    
        </subnodes>
    </node>
    

    我希望它的JSON格式如下:

    {
      "nodeid" : "34",
      "text" : "First level",
      "children" : [{
       "nodeid" : "1",
       "text" : "Content ...",
       "leaf" : true
            ,"children" : [{
       "nodeid" : "2",
       "text" : "Second",
       "leaf" : true
            ,"children" : [{
               "nodeid" : "3",
               "text" : "Third",
               "leaf" : true
        }**,**]
    

    但是在最后一个孩子后面总是有一个逗号。使用FreeMarker,有一种方法可以查明节点是否有父节点、子节点或其他类似节点的内容?父节点?孩子们。但没有机会发现,如果有兄弟姐妹。

    如果当前节点有兄弟节点,FreeMarker如何知道?

    1 回复  |  直到 11 年前
        1
  •  1
  •   winsent    14 年前

    列表循环中有两个特殊的循环变量:

    项目索引 :这是一个数值,包含循环中当前项的索引。

    下一步 :布尔值,指示当前项是否为序列中的最后一项。

    例子:

    <#assign seq = ["winter", "spring", "summer", "autumn"]>
    <#list seq as x>
      ${x_index + 1}. ${x}<#if x_has_next>,</#if>
    </#list>
    

    http://freemarker.sourceforge.net/docs/ref_directive_list.html