XmlSlurper: How to change the text of a dynamic node

夙愿已清 提交于 2019-12-08 19:36:23

问题


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


回答1:


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 )


来源:https://stackoverflow.com/questions/16061762/xmlslurper-how-to-change-the-text-of-a-dynamic-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!