Groovy:从Closure对象构建XML

时间:2013-09-15 01:02:20

标签: java xml groovy

我正在从像这样的对象构建XML:

def buildRequestParameters()
        {
            def requestParametersXML = {
                RequestParameters {
                    IgnoreEditWarnings("false")
                    Type("SaveWithoutValidation")
                    ContractNumber("")
                    Date("null")
                    Status("null")
                    RecordHTTPRequest("false")
                }
            }

            def requestParameters = StreamingMarkupBuilder.bind(requestParametersXML)
            return requestParameters
        }

在将它绑定到StreamMarkupBuilder之前,我需要在此对象中添加另一个element/node 如何更新和访问闭包对象元素?

if(someCondition)
{
  Add another element to RequestParameters //???
} 
def requestParameters = StreamingMarkupBuilder.bind(requestParametersXML)
  

注意:今天是Groovy的第二天

1 个答案:

答案 0 :(得分:1)

在构建xml时添加条件:

import groovy.xml.*

def buildRequestParameters(params)
{
    def requestParametersXML = {
        RequestParameters {
            IgnoreEditWarnings("false")
            Type("SaveWithoutValidation")
            ContractNumber("")
            Date("null")
            Status("null")
            if (params.Element1) {
              Element1 {
                Element11( params.Element1.Element11 )
              }
            }
            RecordHTTPRequest("false")
        }
    }

    def requestParameters = new StreamingMarkupBuilder().bind(requestParametersXML)
    return requestParameters
}

println buildRequestParameters( [:] )

println buildRequestParameters( [Element1: [Element11: "element11 value"]] )