XmlSlurper: How to change the text of a dynamic node
Asked Answered
A

1

6
<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.

Aurlie answered 17/4, 2013 at 13:44 Comment(0)
F
11

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 )
Fant answered 17/4, 2013 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.