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

有帮助吗?

解决方案

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 )
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top