简体   繁体   English

Groovy MarkupBuilder:如何创建标记和附加字符串

[英]Groovy MarkupBuilder : How to create markup and append string

I am using the Groovy MarkupBuilder to create some XML. 我正在使用Groovy MarkupBuilder创建一些XML。

In my scenario I get an xml string which is essentially the body of the xml document and then I want to surround it with some other stuff. 在我的场景中,我得到了一个xml字符串,它本质上是xml文档的主体,然后我想用其他东西将其包围。

Something like this.... 像这样...

def xmltext = '''<node><name short="yes">tim</name><fun>maybe</fun></node>'''
def body = new XmlSlurper(false,false).parseText( xmltext )

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.mkp.xmlDeclaration version: '1.0', encoding: 'UTF-8'
xml.'cre:InputParamters'('xmlns:cre': 'http://xmlns.oracle.com/apps/ar/soaprovider/plsql/ar_invoice_api_pub/create_single_invoice/') {
    xml.'cre:P_P_TRX_HEADER_TBL' {
        xml.'cre:P_TRX_HEADER_TBL_ITEM' {
            map 'cre:TRX_HEADER_ID', '',xml
            map 'cre:TRX_DATE', requestPayload?.invoiceDate, xml
            map 'cre:TRX_CURRENCY', requestPayload?.currencyCode, xml
            map 'cre:TRX_CLASS', 'INV', xml
            map 'cre:CUST_TRX_TYPE_ID', '1034', xml
            map 'cre:BILL_TO_CUSTOMER_ID', '147055', xml
        }
    }
    <<APPEND ELEMENTS FROM XML STRING HERE>>
}

private map (Object field, Object value, MarkupBuilder xml) {
    if (value) {
        xml."$field"(value)
    }
}

return writer.toString()

Could someone help me with the bit 'APPEND ELEMENTS FROM XML STRING HERE' and how to get that the work for me? 有人可以帮我“从XML STRING到这里添加元素”,以及如何为我工作吗?

thanks 谢谢

Here is the changed script: 这是更改后的脚本:

Note that you have used some variable to get the values. 请注意,您已经使用了一些变量来获取值。 To demonstrate I have used fixed values below which you may be able to replace it. 为了说明我使用了固定值,您可以在固定值以下替换它。

import groovy.xml.*
def xmltext = '''<node><name short="yes">tim</name><fun>maybe</fun></node>'''

def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def xml = builder.bind {
    mkp.xmlDeclaration()    
    namespaces << [cre:'http://xmlns.oracle.com/apps/ar/soaprovider/plsql/ar_invoice_api_pub/create_single_invoice/']
    cre.InputParamters{
        cre.P_P_TRX_HEADER_TBL {
            cre.P_TRX_HEADER_TBL_ITEM {
                cre.TRX_HEADER_ID ('')
                cre.TRX_DATE ('2017-02-17')
                cre.TRX_CURRENCY( 'USD')
                cre.TRX_CLASS('INV')
                cre.CUST_TRX_TYPE_ID( '1034')
                cre.BILL_TO_CUSTOMER_ID( '147055')
            }
        }
        mkp.yieldUnescaped xmltext
    }
}

println XmlUtil.serialize(xml)

You may try it quickly online Demo 您可以尝试很快的在线演示

Output 产量

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM