[英]How to read xml node and replace value of node in groovy script?
我正在寻找以下所需的 Groovy 代码。
我需要读取 Xml 节点并将节点的值替换为某个值。 假设我需要用 $ 替换数字。
输入 Xml:
<?xml version='1.0' encoding='UTF-8'?><person>
<dob>19-01-1987</dob>
<nationalidinformation>
<nationalid>14-9875-6a</nationalid>
</nationalidinformation>
</person>
预期 Xml:
<?xml version='1.0' encoding='UTF-8'?><person>
<dob>$$-$$-$$$$</dob>
<nationalidinformation>
<nationalid>$$-$$$$-$a</nationalid>
</nationalidinformation>
</person>
请帮我提供代码以获取此信息。在此先感谢
def Message processData(Message message) {
def body_xml= message.getBody(java.lang.String) as String
Node root = new XmlParser().parseText(body_xml)
root.'**'.findAll { it.name.text() == 'dob' }.toString().replaceAll("\\d", "$")
def xml = XmlUtil.serialize(root)
message.setBody(xml)
return message
}
好的,我不知道Message
是什么,但假设您可以在其上调用getBody()
和setBody(x)
,以下应该可以工作(我添加了注释来解释更改):
import groovy.xml.*
// Don't need a def, as we're specifying a type
Message processData(Message message) {
// This is shorter than you had it, and should still work
String body_xml = message.getBody(String)
def root = new XmlParser().parseText(body_xml)
// Find the first <dob> element, and set it's value to $
root.'**'.find { it.name() == 'dob' }.value = '$'
// Serialize it back (this will call setBody())
message.body = XmlUtil.serialize(root)
// Last line returns the value, no need for `return`
message
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.