如果使用 freemarker 的源中不存在元素,则省略上一行的逗号

Omitting comma from previous line if element not present in the source using freemarker

我正在使用 freemarker 进行 xml 到 json 的转换。我的Xml正在关注

<ResponseMetadata> 
   <ResponseCode>HS000000</ResponseCode> 
   <ResponseDescriptionText>Success</ResponseDescriptionText> 
</ResponseMetadata>

我正在使用以下 ftl 进行转换。

<#assign data =  xml['child::node()']>
{      
  "ResponseMetadata":{  
     <#if (data.ResponseCode)?has_content>"ResponseCode":"${data.ResponseCode}",</#if>
     <#if (data.ResponseDescriptionText)?has_content>"ResponseDescriptionText":"${data.ResponseDescriptionText}",</#if>
     <#if (data.TDSResponseDescriptionText)?has_content>,"TDSResponseDescriptionText":"${data.TDSResponseDescriptionText}" </#if>   
  }
}

我得到以下输出,其中逗号 (,) 在第二个元素之后打印,因为 XML 源中不存在第三个元素。

"ResponseMetadata":{  
     "ResponseCode":"HS000000",
     "ResponseDescriptionText":"Success" ,   
  }
}

如果找不到如下元素,我希望输出不带逗号:

"ResponseMetadata":{  
     "ResponseCode":"HS000000",
     "ResponseDescriptionText":"Success"   
  }
}

我的问题是当源中不存在下一个元素时如何省略逗号 xml。谢谢

如果您只想将 XML 更改为 JSON,您可以简化代码,列出 xml 中的所有节点并使用 sep:

<#assign data =  xml['child::node()']/>
{      
    "ResponseMetadata":{  
    <#list data?children as field>
        "${field?node_name}":"${field}"<#sep>,</#sep>
    </#list>
    }
}

结果:

{      
    "ResponseMetadata":{  
        "ResponseCode":"HS000000",
        "ResponseDescriptionText":"Success"
    }
}

为 XML here

寻找更多 freemarker build-ins 函数

终于解决了这个问题。解决方案是声明一个序列并添加具有内容的元素并解析为列表。解决方案代码如下

<#assign data =  xml['child::node()']>

    {      
      "ResponseMetadata":{  
      <#assign y = []>
         <#if (data.ResponseCode)?has_content>
                <#assign var1>"ResponseCode":"${data.ResponseCode}"</#assign>
                <#assign y = y + [ var1 ] />
         </#if>
         <#if (data.ResponseDescriptionText)?has_content>
             <#assign var2>"ResponseDescriptionText":"${data.ResponseDescriptionText}"</#assign>
             <#assign y = y + [ var2 ] />
         </#if>
         <#if (data.TDSResponseDescriptionText)?has_content>
             <#assign var3>"TDSResponseDescriptionText":"${data.TDSResponseDescriptionText}" </#assign>
             <#assign y = y + [ var3 ] />
         </#if>   

        <#list y as x>
            ${x}<#sep>,</#sep>
        </#list>

      }
    }