当未使用或设置节点内定义的 Freemarker 变量时,删除 XML 节点

Remove XML Node when Freemarker Variable defined inside that node is not used or set

我的 XML 中定义了 Freemarker 变量 ${xyz},如下例所示。在针对地图处理此 XML 后,我用相关值替换了 Freemarker 变量。

我想删除那些 XML 个没有使用 freemarker 变量的节点。

示例场景: XML 以下具有 Freemarker 变量 ${xyz}。我在其中也有空节点示例 ShouldNotDelete 节点。

Freemarker 模板:

<property>
   <Address>
        <Organisation>${Organisation?c}</Organisation>
        <BuildingName>${BuildingName?c}</BuildingName>              
        <Town>${Town?c}</Town>
        <PostCode>${PostCode?c}</PostCode>
  </Address>
  <ShouldNotDelete></ShouldNotDelete>
</property>

我有地图

Map { “Organisation” : “abc” ,  “PostCode” : “ME165AB” }

此地图中缺少城镇和建筑物名称。

在处理 Map 并将相关值放入上面 XML 之后,我得到以下结果 XML:

结果XML:

<property>
   <Address>
        <Organisation>abc</Organisation>
        <BuildingName></BuildingName>               
        <Town></Town>
        <PostCode>ME165AB</PostCode>
  </Address>
  <ShouldNotDelete></ShouldNotDelete>
</property>

我想删除未使用的 freemarker 节点。在上述情况下,应删除 Town 和 BuildingName 节点。因此,所需的理想输出如下:

需要理想的结果输出:

<property>
   <Address>
        <Organisation>abc</Organisation>
        <PostCode>ME165AB</PostCode>
  </Address>
  <ShouldNotDelete></ShouldNotDelete>
</property>

任何人都可以通过使用 Freemarker 模板语言(例如在节点之前使用 <#if > <#else>)或使用 Java 逻辑来提出一个理想的答案。

你可以试试这个:

<property>
   <Address>
         <#if Organisation??>
             <Organisation>${Organisation?c}</Organisation>
         </#if>         
  </Address>
  <ShouldNotDelete></ShouldNotDelete>
</property>