需要使用Groovy更新XML标记

时间:2014-08-18 11:14:51

标签: xml groovy

我在XML下面需要更新一些标签值,例如' CUSIP',' FUND'。我正在使用下面的代码,但它没有帮助我。

<?xml version="1.0" encoding="UTF-8"?>
<TRANSACTIONS ASOF_DATE="4/2/2014" CREATE_DATE="4/2/2014" RECORDS="1">
    <TRADE>
        <ACCRUAL_DT>4/1/2014</ACCRUAL_DT>
        <COUNTERPARTY_CODE>1627</COUNTERPARTY_CODE>
        <CUSIP>31384WPS3</CUSIP>
        <DESC_INSTMT>CREDIT INDUSTRIEL ET COMMERCIAL (N</DESC_INSTMT>
        <DESK>a</DESK>
        <DESK_TYPE>GEN</DESK_TYPE>
        <DTM_2A7>7</DTM_2A7>
        <EXECUTION_TIME>4/1/2014 10:03:06.000</EXECUTION_TIME>
        <EXEC_TIME_SOURCE>A</EXEC_TIME_SOURCE>
        <FUND>VIMVP-FI</FUND>
        <INT_AT_MATURITY>536.6666666667</INT_AT_MATURITY>
        <INVNUM>-911223</INVNUM>
        <TRDCHARGE_set SIZE="2">
        - <TRDCHARGE>
            <CALC_TYPE>FLAT</CALC_TYPE> 
            <CATEGORY>CLRF</CATEGORY> 
           <TRDCHARGE_AMOUNT>150.0000000000</TRDCHARGE_AMOUNT>           <RATE>0.0000000000</RATE> 
          <TRDCHARGE_SCHEDULE_ID>-111111.0000000000</TRDCHARGE_SCHEDULE_ID> 
         </TRDCHARGE>
      - <TRDCHARGE>
          <CALC_TYPE>FLAT</CALC_TYPE> 
          <CATEGORY>LOCL</CATEGORY> 
          <RATE>0.0000000000</RATE> 
          <TRDCHARGE_AMOUNT>50.0000000000</TRDCHARGE_AMOUNT> 
          <TRDCHARGE_SCHEDULE_ID>-111111.0000000000</TRDCHARGE_SCHEDULE_ID> 
      </TRDCHARGE>
    </TRDCHARGE_set>
    </TRADE>

我使用下面的代码来做同样的事情 -

def xmlFile = "D:\\Invesco\\Alladin\\Test Data Files\\Input\\Transaction_FI.xml"
def xml = new XmlParser(false, false).parse(xmlFile)

xml.'**'.'Trade'.each{

it.@FUND = 'CASH'
it.@INVNUM = '-675'
it.@CUSIP = '3B56GTUNN'

}

我还需要为类别LOCL更改TRDCHARGE的标记值

1 个答案:

答案 0 :(得分:0)

这有效:

new XmlParser().parse(xmlFile).with { x ->
    x.TRADE.each { trade ->
        trade.children().find { it -> it.name() == 'FUND' }?.value = 'CASH'
        trade.children().find { it -> it.name() == 'INVNUM' }?.value = '-675'
        trade.children().find { it -> it.name() == 'CUSIP' }?.value = '3B56GTUNN'        
    }
    println XmlUtil.serialize(x)
}