Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSlurper: How to change the text of a dynamic node

<Messdaten>
  <EL_NR>NAYP99</EL_NR>
  <EL_NR_Original/>
  <Erfassungsdatum>2012-12-12 11:58:54.000</Erfassungsdatum>
  <Massnahme>Lot_Hold</Massnahme>
  <Anzahl_x0020_R>50</Anzahl_x0020_R>
  <FEHLER>OK</FEHLER>
  <SEQ>72</SEQ>
</Messdaten>

That is my XML and i want to change the value of node 'Anzahl_x0020_R'. The problem is, at runtime i don't know the exact name. I only know that the node to change will start with 'Anzahl'. So i did this:

messdatenXML.childNodes().each { merkmal ->
    if (merkmal.name.contains('Anzahl')) {
        messdatenXML.merkmal = "my_new_value";
    }
}

The thing is, it doesn't work, the value will stay the same. If i do:

messdatenXML.Anzahl_x0020_R = "my_new_value"

it will work but as i said before, i don't know the exact name at runtime.

like image 807
Endogen Avatar asked Apr 17 '13 13:04

Endogen


1 Answers

I believe you need to use replaceBody like so:

messdatenXML.'**'.findAll { it.name().startsWith 'Anzahl' }.each { node ->
  node.replaceBody 'my new value'
}
println groovy.xml.XmlUtil.serialize( messdatenXML )
like image 66
tim_yates Avatar answered Nov 15 '22 09:11

tim_yates