开发者

templating: removing the elements that doesn't have the data

开发者 https://www.devze.com 2023-03-13 02:31 出处:网络
I am using the Groovy\'s xml templating feature. Below is my template and binding(s). Some times I doesn\'t have any value for the LastName. I would like groovy to not create the element if it doesn\'

I am using the Groovy's xml templating feature. Below is my template and binding(s). Some times I doesn't have any value for the LastName. I would like groovy to not create the element if it doesn't have non-empty data. Can someone suggest how to do it?

Template

<PersonName nameIdentifier="Current">
     <FirstName>${FirstName}</FirstName>
     <LastName>${LastName}</LastName>
</PersonName>
开发者_开发百科

Binding

def binding1 = ['FirstName':FirstName ,'LastName':'LastName']
def binding2 = ['FirstName':FirstName ,'LastName':'']

Code

public static String createXml(String templateResourceName, def bindings)
    {
        def engine = new XmlTemplateEngine()
        def output = engine.createTemplate(getResource(templateResourceName)).make(bindings)

        return output.toString()
    }


I think this can work:

<% print LastName != null ? "<LastName>"+LastName+"</LastName>" : "" %>

But this is the 1st time I heard of this feature, so if it does it will be a lucky guess ...

Edit: Tried it out a bit on the Groovy web console - this should work:

def text = '<PersonName nameIdentifier="Current">\n<FirstName>${FirstName}</FirstName>\n<% print LastName != "" ? "<LastName>"+LastName+"</LastName>\\n" : "" %></PersonName>'

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号