Cyril
Cyril

Reputation: 159

Groovy, update XML

I'm newbie in Groovy and have to accomplish a task for some Jenkins configuration. Please, help me with xml parsing. Just in order to simplify the problem(originally it's a huge Jenkins config.xml file), let's take:

def input = '''
              <shopping>
                  <category>
                      <item>Pen</item>
                      <color>Red</color>
                  </category>
              <category>
                      <item>Pencil</item>
                      <color>Black</color>
                  </category>
                  <category>
                      <item>Paper</item>
                      <color>White</color>
                  </category>
              </shopping>
    '''

The target is to change color for Pen only.

I'm trying:

def root = new XmlParser().parseText(input)
def supplies = root.category.find{ it.text() == 'Pen' } 
supplies.parent().color.value() = 'Changed'

Looks so simple but I'm totally lost :( Appreciate any help.

Upvotes: 0

Views: 4288

Answers (2)

dmahapatro
dmahapatro

Reputation: 50245

....Or use XmlSlurper to simplify usage of color[0] and text().

def root = new XmlSlurper().parseText(input)
def supplies = root.category.find{ it.item == 'Pen' }
supplies.color = 'Changed'

Upvotes: 2

Ori Dar
Ori Dar

Reputation: 19000

Almost there...

def root = new XmlParser().parseText(input)
def supplies = root.category.find{ it.item.text() == 'Pen' }
supplies.color[0].value = 'Changed'

The thing to note is that color is a Node List whose first node is a text node

Upvotes: 3

Related Questions