Replace Value in XML with ParseText by using groovy script

Bell Aimsaard :

I want to update value in XML with parseText.

This is my XML

def xmlText  = '''<BookRoot>
    <Book>
        <startDate>2005-02-14T00:00:00.000</startDate>
        <endDate>2015-01-31T00:00:00.000</endDate>
        <Author>Manu</Author>
    </Book>
    <Book>
        <startDate>2005-02-01T00:00:00.000</startDate>
        <endDate>9999-12-31T00:00:00.000</endDate>
        <Author>Liverpool</Author>
    </Book>
</BookRoot>'''

def xml = new XmlSlurper().parseText(xmlText);

This is expected result.

<BookRoot>
    <Book>
        <startDate>CurrentDate</startDate>
        <endDate>FutureDate</endDate>
        <Author>Manu</Author>
    </Book>
    <Book>
        <startDate>CurrentDate</startDate>
        <endDate>FutureDate</endDate>
        <Author>Liverpool</Author>
    </Book>
</BookRoot>

I tried to use this code

xml.Book.each{ it->
    it.startDate[0].value = 'CurrentDate'
    it.endDate[0].value = 'FutureDate'
  }

println XmlUtil.serialize(xml)

but startDate's value and endDate's value are not updated.

cfrick :

You have to replaceBody on the tags. E.g.

    it.startDate.replaceBody 'CurrentDate'

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=335349&siteId=1